blob: 0d29b2bb3e016ed97df7689c6dc54bec1d372d2e [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)
1186 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001187 if (type.getQualifier().isPipeInput())
1188 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001189 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001190 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001191
1192 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001193 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001194 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001195 return spv::StorageClassAtomicCounter;
1196 if (type.containsOpaque())
1197 return spv::StorageClassUniformConstant;
1198 }
1199
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001200 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001201 type.getQualifier().isShaderRecord()) {
1202 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001203 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001204
John Kessenichbed4e4f2017-09-08 02:38:07 -06001205 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001206 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001207 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001208 }
1209
1210 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001211 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001212 return spv::StorageClassPushConstant;
1213 if (type.getBasicType() == glslang::EbtBlock)
1214 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001215 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001216 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001217
1218 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001219 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1220 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1221 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001222 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001223#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001224 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1225 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1226 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1227 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1228 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001229#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001230 default:
1231 assert(0);
1232 break;
1233 }
1234
1235 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001236}
1237
John Kessenich5611c6d2018-04-05 11:25:02 -06001238// Add capabilities pertaining to how an array is indexed.
1239void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1240 const glslang::TType& indexType)
1241{
John Kessenichb9197c82019-08-11 07:41:45 -06001242#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001243 if (indexType.getQualifier().isNonUniform()) {
1244 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001245 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001246 if (baseType.getBasicType() == glslang::EbtSampler) {
1247 if (baseType.getQualifier().hasAttachment())
1248 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001249 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001250 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001251 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001252 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1253 else if (baseType.isImage())
1254 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1255 else if (baseType.isTexture())
1256 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1257 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1258 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1259 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1260 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1261 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1262 }
1263 } else {
1264 // assume a dynamically uniform index
1265 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001266 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001267 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001268 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001269 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001270 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001271 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001272 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001273 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001274 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001275 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001276 }
1277 }
John Kessenichb9197c82019-08-11 07:41:45 -06001278#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001279}
1280
qining25262b32016-05-06 17:25:16 -04001281// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001282// descriptor set.
1283bool IsDescriptorResource(const glslang::TType& type)
1284{
John Kessenichf7497e22016-03-08 21:36:22 -07001285 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001286 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001287 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001288 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001289 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001290
1291 // non block...
1292 // basically samplerXXX/subpass/sampler/texture are all included
1293 // if they are the global-scope-class, not the function parameter
1294 // (or local, if they ever exist) class.
1295 if (type.getBasicType() == glslang::EbtSampler)
1296 return type.getQualifier().isUniformOrBuffer();
1297
1298 // None of the above.
1299 return false;
1300}
1301
John Kesseniche0b6cad2015-12-24 10:30:13 -07001302void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1303{
1304 if (child.layoutMatrix == glslang::ElmNone)
1305 child.layoutMatrix = parent.layoutMatrix;
1306
1307 if (parent.invariant)
1308 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001309 if (parent.flat)
1310 child.flat = true;
1311 if (parent.centroid)
1312 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001313#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001314 if (parent.nopersp)
1315 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001316 if (parent.explicitInterp)
1317 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001318 if (parent.perPrimitiveNV)
1319 child.perPrimitiveNV = true;
1320 if (parent.perViewNV)
1321 child.perViewNV = true;
1322 if (parent.perTaskNV)
1323 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001324 if (parent.patch)
1325 child.patch = true;
1326 if (parent.sample)
1327 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001328 if (parent.coherent)
1329 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001330 if (parent.devicecoherent)
1331 child.devicecoherent = true;
1332 if (parent.queuefamilycoherent)
1333 child.queuefamilycoherent = true;
1334 if (parent.workgroupcoherent)
1335 child.workgroupcoherent = true;
1336 if (parent.subgroupcoherent)
1337 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001338 if (parent.shadercallcoherent)
1339 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001340 if (parent.nonprivate)
1341 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001342 if (parent.volatil)
1343 child.volatil = true;
1344 if (parent.restrict)
1345 child.restrict = true;
1346 if (parent.readonly)
1347 child.readonly = true;
1348 if (parent.writeonly)
1349 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001350#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001351}
1352
John Kessenichf2b7f332016-09-01 17:05:23 -06001353bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001354{
John Kessenich7b9fa252016-01-21 18:56:57 -07001355 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001356 // - struct members might inherit from a struct declaration
1357 // (note that non-block structs don't explicitly inherit,
1358 // only implicitly, meaning no decoration involved)
1359 // - affect decorations on the struct members
1360 // (note smooth does not, and expecting something like volatile
1361 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001362 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001363 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001364}
1365
John Kessenich140f3df2015-06-26 16:58:36 -06001366//
1367// Implement the TGlslangToSpvTraverser class.
1368//
1369
John Kessenich8985fc92020-03-03 10:25:07 -07001370TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1371 const glslang::TIntermediate* glslangIntermediate,
1372 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1373 TIntermTraverser(true, false, true),
1374 options(options),
1375 shaderEntry(nullptr), currentFunction(nullptr),
1376 sequenceDepth(0), logger(buildLogger),
1377 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1378 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1379 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001380 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1381 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001382{
1383 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1384
1385 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001386 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1387 glslangIntermediate->getVersion());
1388
John Kessenich121853f2017-05-31 17:11:16 -06001389 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001390 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001391 builder.setSourceFile(glslangIntermediate->getSourceFile());
1392
1393 // Set the source shader's text. If for SPV version 1.0, include
1394 // a preamble in comments stating the OpModuleProcessed instructions.
1395 // Otherwise, emit those as actual instructions.
1396 std::string text;
1397 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1398 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001399 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001400 text.append("// OpModuleProcessed ");
1401 text.append(processes[p]);
1402 text.append("\n");
1403 } else
1404 builder.addModuleProcessed(processes[p]);
1405 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001406 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001407 text.append("#line 1\n");
1408 text.append(glslangIntermediate->getSourceText());
1409 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001410 // Pass name and text for all included files
1411 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1412 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1413 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001414 }
John Kessenich140f3df2015-06-26 16:58:36 -06001415 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001416
1417 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1418 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1419
1420 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1421 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001422 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001423 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001424 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001425 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001426 memoryModel = spv::MemoryModelVulkanKHR;
1427 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001428 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001429 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001430 builder.setMemoryModel(addressingModel, memoryModel);
1431
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001432 if (glslangIntermediate->usingVariablePointers()) {
1433 builder.addCapability(spv::CapabilityVariablePointers);
1434 }
1435
John Kessenicheee9d532016-09-19 18:09:30 -06001436 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1437 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001440 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1441 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001442 builder.addSourceExtension(it->c_str());
1443
1444 // Add the top-level modes for this shader.
1445
John Kessenich92187592016-02-01 13:45:25 -07001446 if (glslangIntermediate->getXfbMode()) {
1447 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001449 }
John Kessenich140f3df2015-06-26 16:58:36 -06001450
1451 unsigned int mode;
1452 switch (glslangIntermediate->getStage()) {
1453 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001454 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001455 break;
1456
John Kessenicha28f7a72019-08-06 07:00:58 -06001457 case EShLangFragment:
1458 builder.addCapability(spv::CapabilityShader);
1459 if (glslangIntermediate->getPixelCenterInteger())
1460 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1461
1462 if (glslangIntermediate->getOriginUpperLeft())
1463 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1464 else
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1466
1467 if (glslangIntermediate->getEarlyFragmentTests())
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1469
1470 if (glslangIntermediate->getPostDepthCoverage()) {
1471 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1473 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1474 }
1475
John Kessenichb9197c82019-08-11 07:41:45 -06001476 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1478
1479#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001480
John Kessenicha28f7a72019-08-06 07:00:58 -06001481 switch(glslangIntermediate->getDepth()) {
1482 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1483 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1484 default: mode = spv::ExecutionModeMax; break;
1485 }
1486 if (mode != spv::ExecutionModeMax)
1487 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001488 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001489 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1490 break;
1491 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1492 break;
1493 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1494 break;
1495 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1496 break;
1497 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1498 break;
1499 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1500 break;
1501 default: mode = spv::ExecutionModeMax;
1502 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001503 }
1504 if (mode != spv::ExecutionModeMax) {
1505 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1506 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1507 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1508 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1509 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1510 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1511 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1512 } else {
1513 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1514 }
1515 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1516 }
John Kessenichb9197c82019-08-11 07:41:45 -06001517#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001518 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001519
John Kessenicha28f7a72019-08-06 07:00:58 -06001520 case EShLangCompute:
1521 builder.addCapability(spv::CapabilityShader);
1522 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1523 glslangIntermediate->getLocalSize(1),
1524 glslangIntermediate->getLocalSize(2));
1525 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1526 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1528 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1529 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1530 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1531 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1532 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1533 }
1534 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001535#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001536 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001537 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001538 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001539
steve-lunarge7412492017-03-23 11:56:07 -06001540 glslang::TLayoutGeometry primitive;
1541
1542 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001543 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1544 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001545 primitive = glslangIntermediate->getOutputPrimitive();
1546 } else {
1547 primitive = glslangIntermediate->getInputPrimitive();
1548 }
1549
1550 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001551 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1552 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1553 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001554 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001555 }
John Kessenich4016e382016-07-15 11:53:56 -06001556 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001557 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1558
John Kesseniche6903322015-10-13 16:29:02 -06001559 switch (glslangIntermediate->getVertexSpacing()) {
1560 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1561 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1562 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001563 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001564 }
John Kessenich4016e382016-07-15 11:53:56 -06001565 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001566 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1567
1568 switch (glslangIntermediate->getVertexOrder()) {
1569 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1570 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001571 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001572 }
John Kessenich4016e382016-07-15 11:53:56 -06001573 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001574 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1575
1576 if (glslangIntermediate->getPointMode())
1577 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001578 break;
1579
1580 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001581 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001582 switch (glslangIntermediate->getInputPrimitive()) {
1583 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1584 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1585 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001586 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001587 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001588 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001589 }
John Kessenich4016e382016-07-15 11:53:56 -06001590 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001591 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001592
John Kessenich140f3df2015-06-26 16:58:36 -06001593 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1594
1595 switch (glslangIntermediate->getOutputPrimitive()) {
1596 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1597 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1598 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001599 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001600 }
John Kessenich4016e382016-07-15 11:53:56 -06001601 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001602 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1603 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1604 break;
1605
Daniel Kochdb32b242020-03-17 20:42:47 -04001606 case EShLangRayGen:
1607 case EShLangIntersect:
1608 case EShLangAnyHit:
1609 case EShLangClosestHit:
1610 case EShLangMiss:
1611 case EShLangCallable:
1612 {
1613 auto& extensions = glslangIntermediate->getRequestedExtensions();
1614 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1615 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1616 builder.addExtension("SPV_KHR_ray_tracing");
1617 }
1618 else {
1619 builder.addCapability(spv::CapabilityRayTracingNV);
1620 builder.addExtension("SPV_NV_ray_tracing");
1621 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001622 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001623 }
Chao Chen3c366992018-09-19 11:41:59 -07001624 case EShLangTaskNV:
1625 case EShLangMeshNV:
1626 builder.addCapability(spv::CapabilityMeshShadingNV);
1627 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1628 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1629 glslangIntermediate->getLocalSize(1),
1630 glslangIntermediate->getLocalSize(2));
1631 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001632 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1633 glslangIntermediate->getVertices());
1634 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1635 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001636
1637 switch (glslangIntermediate->getOutputPrimitive()) {
1638 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1639 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1640 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1641 default: mode = spv::ExecutionModeMax; break;
1642 }
1643 if (mode != spv::ExecutionModeMax)
1644 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1645 }
1646 break;
1647#endif
1648
John Kessenich140f3df2015-06-26 16:58:36 -06001649 default:
1650 break;
1651 }
John Kessenich140f3df2015-06-26 16:58:36 -06001652}
1653
John Kessenichfca82622016-11-26 13:23:20 -07001654// Finish creating SPV, after the traversal is complete.
1655void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001656{
John Kessenichf04c51b2018-08-03 15:56:12 -06001657 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001658 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001659 builder.setBuildPoint(shaderEntry->getLastBlock());
1660 builder.leaveFunction();
1661 }
1662
John Kessenich7ba63412015-12-20 17:37:07 -07001663 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001664 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1665 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001666
David Neto8c3d5b42019-10-21 14:50:31 -04001667 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001668 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001669 // Note: WebGPU code generation must have the opportunity to aggressively
1670 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001671 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001672}
1673
John Kessenichfca82622016-11-26 13:23:20 -07001674// Write the SPV into 'out'.
1675void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001676{
John Kessenichfca82622016-11-26 13:23:20 -07001677 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001678}
1679
1680//
1681// Implement the traversal functions.
1682//
1683// Return true from interior nodes to have the external traversal
1684// continue on to children. Return false if children were
1685// already processed.
1686//
1687
1688//
qining25262b32016-05-06 17:25:16 -04001689// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001690// - uniform/input reads
1691// - output writes
1692// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1693// - something simple that degenerates into the last bullet
1694//
1695void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1696{
qining75d1d802016-04-06 14:42:01 -04001697 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001698 if (symbol->getType().isStruct())
1699 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1700
qining75d1d802016-04-06 14:42:01 -04001701 if (symbol->getType().getQualifier().isSpecConstant())
1702 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1703
John Kessenich140f3df2015-06-26 16:58:36 -06001704 // getSymbolId() will set up all the IO decorations on the first call.
1705 // Formal function parameters were mapped during makeFunctions().
1706 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001707
John Kessenich7ba63412015-12-20 17:37:07 -07001708 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001709 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001710 // Consider adding to the OpEntryPoint interface list.
1711 // Only looking at structures if they have at least one member.
1712 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1713 spv::StorageClass sc = builder.getStorageClass(id);
1714 // Before SPIR-V 1.4, we only want to include Input and Output.
1715 // Starting with SPIR-V 1.4, we want all globals.
1716 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1717 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001718 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001719 }
John Kessenich5f77d862017-09-19 11:09:59 -06001720 }
John Kessenich9c14f772019-06-17 08:38:35 -06001721
Daniel Kochdb32b242020-03-17 20:42:47 -04001722 // If the SPIR-V type is required to be different than the AST type
1723 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001724 // translate now from the SPIR-V type to the AST type, for the consuming
1725 // operation.
1726 // Note this turns it from an l-value to an r-value.
1727 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1728 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1729 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001730 }
1731
1732 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001733 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001734 // Prepare to generate code for the access
1735
1736 // L-value chains will be computed left to right. We're on the symbol now,
1737 // which is the left-most part of the access chain, so now is "clear" time,
1738 // followed by setting the base.
1739 builder.clearAccessChain();
1740
1741 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001742 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001743 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001744 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001745 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001746 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001747 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001748 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001749 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1750 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001751 builder.setAccessChainRValue(id);
1752 else
1753 builder.setAccessChainLValue(id);
1754 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001755
John Kessenichb9197c82019-08-11 07:41:45 -06001756#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001757 // Process linkage-only nodes for any special additional interface work.
1758 if (linkageOnly) {
1759 if (glslangIntermediate->getHlslFunctionality1()) {
1760 // Map implicit counter buffers to their originating buffers, which should have been
1761 // seen by now, given earlier pruning of unused counters, and preservation of order
1762 // of declaration.
1763 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1764 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1765 // Save possible originating buffers for counter buffers, keyed by
1766 // making the potential counter-buffer name.
1767 std::string keyName = symbol->getName().c_str();
1768 keyName = glslangIntermediate->addCounterBufferName(keyName);
1769 counterOriginator[keyName] = symbol;
1770 } else {
1771 // Handle a counter buffer, by finding the saved originating buffer.
1772 std::string keyName = symbol->getName().c_str();
1773 auto it = counterOriginator.find(keyName);
1774 if (it != counterOriginator.end()) {
1775 id = getSymbolId(it->second);
1776 if (id != spv::NoResult) {
1777 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001778 if (counterId != spv::NoResult) {
1779 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001780 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001781 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001782 }
1783 }
1784 }
1785 }
1786 }
1787 }
John Kessenich155d3512019-08-08 23:29:20 -06001788#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001789}
1790
1791bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1792{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001793 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001794 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1795 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1796 }
1797 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1798 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1799 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001800
qining40887662016-04-03 22:20:42 -04001801 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1802 if (node->getType().getQualifier().isSpecConstant())
1803 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1804
John Kessenich140f3df2015-06-26 16:58:36 -06001805 // First, handle special cases
1806 switch (node->getOp()) {
1807 case glslang::EOpAssign:
1808 case glslang::EOpAddAssign:
1809 case glslang::EOpSubAssign:
1810 case glslang::EOpMulAssign:
1811 case glslang::EOpVectorTimesMatrixAssign:
1812 case glslang::EOpVectorTimesScalarAssign:
1813 case glslang::EOpMatrixTimesScalarAssign:
1814 case glslang::EOpMatrixTimesMatrixAssign:
1815 case glslang::EOpDivAssign:
1816 case glslang::EOpModAssign:
1817 case glslang::EOpAndAssign:
1818 case glslang::EOpInclusiveOrAssign:
1819 case glslang::EOpExclusiveOrAssign:
1820 case glslang::EOpLeftShiftAssign:
1821 case glslang::EOpRightShiftAssign:
1822 // A bin-op assign "a += b" means the same thing as "a = a + b"
1823 // where a is evaluated before b. For a simple assignment, GLSL
1824 // says to evaluate the left before the right. So, always, left
1825 // node then right node.
1826 {
1827 // get the left l-value, save it away
1828 builder.clearAccessChain();
1829 node->getLeft()->traverse(this);
1830 spv::Builder::AccessChain lValue = builder.getAccessChain();
1831
1832 // evaluate the right
1833 builder.clearAccessChain();
1834 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001835 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001836
1837 if (node->getOp() != glslang::EOpAssign) {
1838 // the left is also an r-value
1839 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001840 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001841
1842 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001843 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001844 TranslateNoContractionDecoration(node->getType().getQualifier()),
1845 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001846 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001847 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1848 node->getType().getBasicType());
1849
1850 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001851 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001852 }
1853
1854 // store the result
1855 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001856 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001857
1858 // assignments are expressions having an rValue after they are evaluated...
1859 builder.clearAccessChain();
1860 builder.setAccessChainRValue(rValue);
1861 }
1862 return false;
1863 case glslang::EOpIndexDirect:
1864 case glslang::EOpIndexDirectStruct:
1865 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001866 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001867 // Get the left part of the access chain.
1868 node->getLeft()->traverse(this);
1869
1870 // Add the next element in the chain
1871
David Netoa901ffe2016-06-08 14:11:40 +01001872 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001873 if (! node->getLeft()->getType().isArray() &&
1874 node->getLeft()->getType().isVector() &&
1875 node->getOp() == glslang::EOpIndexDirect) {
1876 // This is essentially a hard-coded vector swizzle of size 1,
1877 // so short circuit the access-chain stuff with a swizzle.
1878 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001879 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001880 int dummySize;
1881 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1882 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001883 glslangIntermediate->getBaseAlignmentScalar(
1884 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001885 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001886
1887 // Load through a block reference is performed with a dot operator that
1888 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1889 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001890 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001891 !node->getLeft()->getType().isArray() &&
1892 node->getOp() == glslang::EOpIndexDirectStruct)
1893 {
1894 spv::Id left = accessChainLoad(node->getLeft()->getType());
1895 builder.clearAccessChain();
1896 builder.setAccessChainLValue(left);
1897 }
1898
David Netoa901ffe2016-06-08 14:11:40 +01001899 int spvIndex = glslangIndex;
1900 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1901 node->getOp() == glslang::EOpIndexDirectStruct)
1902 {
1903 // This may be, e.g., an anonymous block-member selection, which generally need
1904 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001905 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1906 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1907 std::vector<int>& remapper = memberRemapper[glslangId];
1908 assert(remapper.size() > 0);
1909 spvIndex = remapper[glslangIndex];
1910 }
David Netoa901ffe2016-06-08 14:11:40 +01001911 }
John Kessenichebb50532016-05-16 19:22:05 -06001912
David Netoa901ffe2016-06-08 14:11:40 +01001913 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001914 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1915 TranslateCoherent(node->getLeft()->getType()),
1916 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001917
1918 // Add capabilities here for accessing PointSize and clip/cull distance.
1919 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001920 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001921 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001922 }
1923 }
1924 return false;
1925 case glslang::EOpIndexIndirect:
1926 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001927 // Array, matrix, or vector indirection with variable index.
1928 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001929 // matrices are arrays of vectors, so will also work for a matrix.
1930 // Will use the access chain's 'component' for variable index into a vector.
1931
1932 // This adapter is building access chains left to right.
1933 // Set up the access chain to the left.
1934 node->getLeft()->traverse(this);
1935
1936 // save it so that computing the right side doesn't trash it
1937 spv::Builder::AccessChain partial = builder.getAccessChain();
1938
1939 // compute the next index in the chain
1940 builder.clearAccessChain();
1941 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001942 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001943
John Kessenich5611c6d2018-04-05 11:25:02 -06001944 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1945
John Kessenich140f3df2015-06-26 16:58:36 -06001946 // restore the saved access chain
1947 builder.setAccessChain(partial);
1948
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001949 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1950 int dummySize;
1951 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1952 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001953 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1954 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001955 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001956 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1957 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001958 }
1959 return false;
1960 case glslang::EOpVectorSwizzle:
1961 {
1962 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001963 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001964 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001965 int dummySize;
1966 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1967 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001968 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1969 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001970 }
1971 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001972 case glslang::EOpMatrixSwizzle:
1973 logger->missingFunctionality("matrix swizzle");
1974 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001975 case glslang::EOpLogicalOr:
1976 case glslang::EOpLogicalAnd:
1977 {
1978
1979 // These may require short circuiting, but can sometimes be done as straight
1980 // binary operations. The right operand must be short circuited if it has
1981 // side effects, and should probably be if it is complex.
1982 if (isTrivial(node->getRight()->getAsTyped()))
1983 break; // handle below as a normal binary operation
1984 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001985 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1986 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001987 builder.clearAccessChain();
1988 builder.setAccessChainRValue(result);
1989 }
1990 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001991 default:
1992 break;
1993 }
1994
1995 // Assume generic binary op...
1996
John Kessenich32cfd492016-02-02 12:37:46 -07001997 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001998 builder.clearAccessChain();
1999 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002000 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002001
John Kessenich32cfd492016-02-02 12:37:46 -07002002 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002003 builder.clearAccessChain();
2004 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002005 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002006
John Kessenich32cfd492016-02-02 12:37:46 -07002007 // get result
John Kessenichead86222018-03-28 18:01:20 -06002008 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002009 TranslateNoContractionDecoration(node->getType().getQualifier()),
2010 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002011 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002012 convertGlslangToSpvType(node->getType()), left, right,
2013 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002014
John Kessenich50e57562015-12-21 21:21:11 -07002015 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002016 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002017 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002018 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002019 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002020 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002021 return false;
2022 }
John Kessenich140f3df2015-06-26 16:58:36 -06002023}
2024
John Kessenich9c14f772019-06-17 08:38:35 -06002025// Figure out what, if any, type changes are needed when accessing a specific built-in.
2026// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2027// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002028std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002029 const glslang::TType& glslangType)
2030{
Daniel Kochdb32b242020-03-17 20:42:47 -04002031 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002032 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002033 case glslang::EbvSubGroupEqMask:
2034 case glslang::EbvSubGroupGeMask:
2035 case glslang::EbvSubGroupGtMask:
2036 case glslang::EbvSubGroupLeMask:
2037 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002038 // these require changing a 64-bit scaler -> a vector of 32-bit components
2039 if (glslangType.isVector())
2040 break;
2041 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2042 builder.makeUintType(64));
2043 return ret;
2044 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002045 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2046 // builtins. During visitBinary we insert a transpose
2047 case glslang::EbvWorldToObject3x4:
2048 case glslang::EbvObjectToWorld3x4: {
2049 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2050 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2051 );
2052 return ret;
2053 }
John Kessenich9c14f772019-06-17 08:38:35 -06002054 default:
2055 break;
2056 }
2057
2058 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2059 return ret;
2060}
2061
2062// For an object previously identified (see getForcedType() and forceType)
2063// as needing type translations, do the translation needed for a load, turning
2064// an L-value into in R-value.
2065spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2066{
2067 const auto forceIt = forceType.find(object);
2068 if (forceIt == forceType.end())
2069 return object;
2070
2071 spv::Id desiredTypeId = forceIt->second;
2072 spv::Id objectTypeId = builder.getTypeId(object);
2073 assert(builder.isPointerType(objectTypeId));
2074 objectTypeId = builder.getContainedTypeId(objectTypeId);
2075 if (builder.isVectorType(objectTypeId) &&
2076 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2077 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2078 // handle 32-bit v.xy* -> 64-bit
2079 builder.clearAccessChain();
2080 builder.setAccessChainLValue(object);
2081 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2082 std::vector<spv::Id> components;
2083 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2084 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2085
2086 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2087 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2088 builder.createCompositeConstruct(vecType, components));
2089 } else {
2090 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2091 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002092 } else if (builder.isMatrixType(objectTypeId)) {
2093 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2094 // and we insert a transpose after loading the original non-transposed builtins
2095 builder.clearAccessChain();
2096 builder.setAccessChainLValue(object);
2097 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2098 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2099
2100 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002101 logger->missingFunctionality("forcing non 32-bit vector type");
2102 }
2103
2104 return object;
2105}
2106
John Kessenich140f3df2015-06-26 16:58:36 -06002107bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2108{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002109 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002110
qining40887662016-04-03 22:20:42 -04002111 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2112 if (node->getType().getQualifier().isSpecConstant())
2113 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2114
John Kessenichfc51d282015-08-19 13:34:18 -06002115 spv::Id result = spv::NoResult;
2116
2117 // try texturing first
2118 result = createImageTextureFunctionCall(node);
2119 if (result != spv::NoResult) {
2120 builder.clearAccessChain();
2121 builder.setAccessChainRValue(result);
2122
2123 return false; // done with this node
2124 }
2125
2126 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002127
2128 if (node->getOp() == glslang::EOpArrayLength) {
2129 // Quite special; won't want to evaluate the operand.
2130
John Kessenich5611c6d2018-04-05 11:25:02 -06002131 // Currently, the front-end does not allow .length() on an array until it is sized,
2132 // except for the last block membeor of an SSBO.
2133 // TODO: If this changes, link-time sized arrays might show up here, and need their
2134 // size extracted.
2135
John Kessenichc9a80832015-09-12 12:17:44 -06002136 // Normal .length() would have been constant folded by the front-end.
2137 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002138 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002139
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002140 spv::Id length;
2141 if (node->getOperand()->getType().isCoopMat()) {
2142 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2143
2144 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2145 assert(builder.isCooperativeMatrixType(typeId));
2146
2147 length = builder.createCooperativeMatrixLength(typeId);
2148 } else {
2149 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2150 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002151 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2152 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002153 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2154 }
John Kessenichc9a80832015-09-12 12:17:44 -06002155
John Kessenich8c869672018-11-28 07:01:37 -07002156 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2157 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2158 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002159 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2160 if (builder.isInSpecConstCodeGenMode()) {
2161 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2162 } else {
2163 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2164 }
2165 }
John Kessenich8c869672018-11-28 07:01:37 -07002166
John Kessenichc9a80832015-09-12 12:17:44 -06002167 builder.clearAccessChain();
2168 builder.setAccessChainRValue(length);
2169
2170 return false;
2171 }
2172
John Kessenichfc51d282015-08-19 13:34:18 -06002173 // Start by evaluating the operand
2174
John Kessenich8c8505c2016-07-26 12:50:38 -06002175 // Does it need a swizzle inversion? If so, evaluation is inverted;
2176 // operate first on the swizzle base, then apply the swizzle.
2177 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002178 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2179 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002180 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2181 invertedType = getInvertedSwizzleType(*node->getOperand());
2182
John Kessenich140f3df2015-06-26 16:58:36 -06002183 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002184 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002185 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002186 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002187 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002188 operandNode = node->getOperand();
2189
2190 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002191
Rex Xufc618912015-09-09 16:42:49 +08002192 spv::Id operand = spv::NoResult;
2193
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002194 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2195
John Kessenichfb4f2332019-08-09 03:49:15 -06002196#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002197 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2198 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002199 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002200 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002201 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002202 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2203 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2204 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002205#endif
2206 {
John Kessenich32cfd492016-02-02 12:37:46 -07002207 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002208 }
John Kessenich140f3df2015-06-26 16:58:36 -06002209
John Kessenichead86222018-03-28 18:01:20 -06002210 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002211 TranslateNoContractionDecoration(node->getType().getQualifier()),
2212 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002213
2214 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002215 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002216 result = createConversion(node->getOp(), decorations, resultType(), operand,
2217 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002218
2219 // if not, then possibly an operation
2220 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002221 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2222 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002223
2224 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002225 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002226 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002227 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002228 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002229
John Kessenich140f3df2015-06-26 16:58:36 -06002230 builder.clearAccessChain();
2231 builder.setAccessChainRValue(result);
2232
2233 return false; // done with this node
2234 }
2235
2236 // it must be a special case, check...
2237 switch (node->getOp()) {
2238 case glslang::EOpPostIncrement:
2239 case glslang::EOpPostDecrement:
2240 case glslang::EOpPreIncrement:
2241 case glslang::EOpPreDecrement:
2242 {
2243 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002244 spv::Id one = 0;
2245 if (node->getBasicType() == glslang::EbtFloat)
2246 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002247#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002248 else if (node->getBasicType() == glslang::EbtDouble)
2249 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002250 else if (node->getBasicType() == glslang::EbtFloat16)
2251 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002252 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2253 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002254 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2255 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002256 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2257 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002258#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002259 else
2260 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002261 glslang::TOperator op;
2262 if (node->getOp() == glslang::EOpPreIncrement ||
2263 node->getOp() == glslang::EOpPostIncrement)
2264 op = glslang::EOpAdd;
2265 else
2266 op = glslang::EOpSub;
2267
John Kessenichead86222018-03-28 18:01:20 -06002268 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002269 convertGlslangToSpvType(node->getType()), operand, one,
2270 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002271 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002272
2273 // The result of operation is always stored, but conditionally the
2274 // consumed result. The consumed result is always an r-value.
2275 builder.accessChainStore(result);
2276 builder.clearAccessChain();
2277 if (node->getOp() == glslang::EOpPreIncrement ||
2278 node->getOp() == glslang::EOpPreDecrement)
2279 builder.setAccessChainRValue(result);
2280 else
2281 builder.setAccessChainRValue(operand);
2282 }
2283
2284 return false;
2285
John Kessenich155d3512019-08-08 23:29:20 -06002286#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002287 case glslang::EOpEmitStreamVertex:
2288 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2289 return false;
2290 case glslang::EOpEndStreamPrimitive:
2291 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2292 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002293 case glslang::EOpRayQueryTerminate:
2294 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2295 return false;
2296 case glslang::EOpRayQueryConfirmIntersection:
2297 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2298 return false;
2299
John Kessenich155d3512019-08-08 23:29:20 -06002300#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002301
2302 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002303 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002304 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002305 }
John Kessenich140f3df2015-06-26 16:58:36 -06002306}
2307
Jeff Bolz53134492019-06-25 13:31:10 -05002308// Construct a composite object, recursively copying members if their types don't match
2309spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2310{
2311 for (int c = 0; c < (int)constituents.size(); ++c) {
2312 spv::Id& constituent = constituents[c];
2313 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2314 spv::Id rType = builder.getTypeId(constituent);
2315 if (lType != rType) {
2316 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2317 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2318 } else if (builder.isStructType(rType)) {
2319 std::vector<spv::Id> rTypeConstituents;
2320 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2321 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002322 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2323 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002324 }
2325 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2326 } else {
2327 assert(builder.isArrayType(rType));
2328 std::vector<spv::Id> rTypeConstituents;
2329 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2330
2331 spv::Id elementRType = builder.getContainedTypeId(rType);
2332 for (int i = 0; i < numrTypeConstituents; ++i) {
2333 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2334 }
2335 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2336 }
2337 }
2338 }
2339 return builder.createCompositeConstruct(resultTypeId, constituents);
2340}
2341
John Kessenich140f3df2015-06-26 16:58:36 -06002342bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2343{
qining27e04a02016-04-14 16:40:20 -04002344 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2345 if (node->getType().getQualifier().isSpecConstant())
2346 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2347
John Kessenichfc51d282015-08-19 13:34:18 -06002348 spv::Id result = spv::NoResult;
John Kessenichbbbd9a22020-03-03 07:21:37 -07002349 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
John Kessenich8985fc92020-03-03 10:25:07 -07002350 spv::Builder::AccessChain complexLvalue; // for holding swizzling l-values too complex for SPIR-V,
2351 // for at out parameter
John Kessenichbbbd9a22020-03-03 07:21:37 -07002352 spv::Id temporaryLvalue = spv::NoResult; // temporary to pass, as proxy for complexLValue
2353
John Kessenich8985fc92020-03-03 10:25:07 -07002354 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2355 invertedType :
2356 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002357
2358 // try texturing
2359 result = createImageTextureFunctionCall(node);
2360 if (result != spv::NoResult) {
2361 builder.clearAccessChain();
2362 builder.setAccessChainRValue(result);
2363
2364 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002365 }
2366#ifndef GLSLANG_WEB
2367 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002368 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002369 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002370 // "imageStore" is a special case, which has no result
2371 return false;
2372 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002373#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002374
John Kessenich140f3df2015-06-26 16:58:36 -06002375 glslang::TOperator binOp = glslang::EOpNull;
2376 bool reduceComparison = true;
2377 bool isMatrix = false;
2378 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002379 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002380
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002381 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2382
John Kessenich140f3df2015-06-26 16:58:36 -06002383 assert(node->getOp());
2384
John Kessenichf6640762016-08-01 19:44:00 -06002385 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002386
2387 switch (node->getOp()) {
2388 case glslang::EOpSequence:
2389 {
2390 if (preVisit)
2391 ++sequenceDepth;
2392 else
2393 --sequenceDepth;
2394
2395 if (sequenceDepth == 1) {
2396 // If this is the parent node of all the functions, we want to see them
2397 // early, so all call points have actual SPIR-V functions to reference.
2398 // In all cases, still let the traverser visit the children for us.
2399 makeFunctions(node->getAsAggregate()->getSequence());
2400
John Kessenich6fccb3c2016-09-19 16:01:41 -06002401 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002402 // anything else gets there, so visit out of order, doing them all now.
2403 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2404
John Kessenich6a60c2f2016-12-08 21:01:59 -07002405 // 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 -06002406 // so do them manually.
2407 visitFunctions(node->getAsAggregate()->getSequence());
2408
2409 return false;
2410 }
2411
2412 return true;
2413 }
2414 case glslang::EOpLinkerObjects:
2415 {
2416 if (visit == glslang::EvPreVisit)
2417 linkageOnly = true;
2418 else
2419 linkageOnly = false;
2420
2421 return true;
2422 }
2423 case glslang::EOpComma:
2424 {
2425 // processing from left to right naturally leaves the right-most
2426 // lying around in the access chain
2427 glslang::TIntermSequence& glslangOperands = node->getSequence();
2428 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2429 glslangOperands[i]->traverse(this);
2430
2431 return false;
2432 }
2433 case glslang::EOpFunction:
2434 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002435 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002436 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002437 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002438 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002439 } else {
2440 handleFunctionEntry(node);
2441 }
2442 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002443 if (inEntryPoint)
2444 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002445 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002446 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002447 }
2448
2449 return true;
2450 case glslang::EOpParameters:
2451 // Parameters will have been consumed by EOpFunction processing, but not
2452 // the body, so we still visited the function node's children, making this
2453 // child redundant.
2454 return false;
2455 case glslang::EOpFunctionCall:
2456 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002457 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002458 if (node->isUserDefined())
2459 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002460 if (result) {
2461 builder.clearAccessChain();
2462 builder.setAccessChainRValue(result);
2463 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002464 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002465
2466 return false;
2467 }
2468 case glslang::EOpConstructMat2x2:
2469 case glslang::EOpConstructMat2x3:
2470 case glslang::EOpConstructMat2x4:
2471 case glslang::EOpConstructMat3x2:
2472 case glslang::EOpConstructMat3x3:
2473 case glslang::EOpConstructMat3x4:
2474 case glslang::EOpConstructMat4x2:
2475 case glslang::EOpConstructMat4x3:
2476 case glslang::EOpConstructMat4x4:
2477 case glslang::EOpConstructDMat2x2:
2478 case glslang::EOpConstructDMat2x3:
2479 case glslang::EOpConstructDMat2x4:
2480 case glslang::EOpConstructDMat3x2:
2481 case glslang::EOpConstructDMat3x3:
2482 case glslang::EOpConstructDMat3x4:
2483 case glslang::EOpConstructDMat4x2:
2484 case glslang::EOpConstructDMat4x3:
2485 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002486 case glslang::EOpConstructIMat2x2:
2487 case glslang::EOpConstructIMat2x3:
2488 case glslang::EOpConstructIMat2x4:
2489 case glslang::EOpConstructIMat3x2:
2490 case glslang::EOpConstructIMat3x3:
2491 case glslang::EOpConstructIMat3x4:
2492 case glslang::EOpConstructIMat4x2:
2493 case glslang::EOpConstructIMat4x3:
2494 case glslang::EOpConstructIMat4x4:
2495 case glslang::EOpConstructUMat2x2:
2496 case glslang::EOpConstructUMat2x3:
2497 case glslang::EOpConstructUMat2x4:
2498 case glslang::EOpConstructUMat3x2:
2499 case glslang::EOpConstructUMat3x3:
2500 case glslang::EOpConstructUMat3x4:
2501 case glslang::EOpConstructUMat4x2:
2502 case glslang::EOpConstructUMat4x3:
2503 case glslang::EOpConstructUMat4x4:
2504 case glslang::EOpConstructBMat2x2:
2505 case glslang::EOpConstructBMat2x3:
2506 case glslang::EOpConstructBMat2x4:
2507 case glslang::EOpConstructBMat3x2:
2508 case glslang::EOpConstructBMat3x3:
2509 case glslang::EOpConstructBMat3x4:
2510 case glslang::EOpConstructBMat4x2:
2511 case glslang::EOpConstructBMat4x3:
2512 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002513 case glslang::EOpConstructF16Mat2x2:
2514 case glslang::EOpConstructF16Mat2x3:
2515 case glslang::EOpConstructF16Mat2x4:
2516 case glslang::EOpConstructF16Mat3x2:
2517 case glslang::EOpConstructF16Mat3x3:
2518 case glslang::EOpConstructF16Mat3x4:
2519 case glslang::EOpConstructF16Mat4x2:
2520 case glslang::EOpConstructF16Mat4x3:
2521 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002522 isMatrix = true;
2523 // fall through
2524 case glslang::EOpConstructFloat:
2525 case glslang::EOpConstructVec2:
2526 case glslang::EOpConstructVec3:
2527 case glslang::EOpConstructVec4:
2528 case glslang::EOpConstructDouble:
2529 case glslang::EOpConstructDVec2:
2530 case glslang::EOpConstructDVec3:
2531 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002532 case glslang::EOpConstructFloat16:
2533 case glslang::EOpConstructF16Vec2:
2534 case glslang::EOpConstructF16Vec3:
2535 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002536 case glslang::EOpConstructBool:
2537 case glslang::EOpConstructBVec2:
2538 case glslang::EOpConstructBVec3:
2539 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002540 case glslang::EOpConstructInt8:
2541 case glslang::EOpConstructI8Vec2:
2542 case glslang::EOpConstructI8Vec3:
2543 case glslang::EOpConstructI8Vec4:
2544 case glslang::EOpConstructUint8:
2545 case glslang::EOpConstructU8Vec2:
2546 case glslang::EOpConstructU8Vec3:
2547 case glslang::EOpConstructU8Vec4:
2548 case glslang::EOpConstructInt16:
2549 case glslang::EOpConstructI16Vec2:
2550 case glslang::EOpConstructI16Vec3:
2551 case glslang::EOpConstructI16Vec4:
2552 case glslang::EOpConstructUint16:
2553 case glslang::EOpConstructU16Vec2:
2554 case glslang::EOpConstructU16Vec3:
2555 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002556 case glslang::EOpConstructInt:
2557 case glslang::EOpConstructIVec2:
2558 case glslang::EOpConstructIVec3:
2559 case glslang::EOpConstructIVec4:
2560 case glslang::EOpConstructUint:
2561 case glslang::EOpConstructUVec2:
2562 case glslang::EOpConstructUVec3:
2563 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002564 case glslang::EOpConstructInt64:
2565 case glslang::EOpConstructI64Vec2:
2566 case glslang::EOpConstructI64Vec3:
2567 case glslang::EOpConstructI64Vec4:
2568 case glslang::EOpConstructUint64:
2569 case glslang::EOpConstructU64Vec2:
2570 case glslang::EOpConstructU64Vec3:
2571 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002572 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002573 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002574 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002575 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002576 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002577 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002578 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002579 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002580 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002581 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002582 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002583 else if (node->getOp() == glslang::EOpConstructStruct ||
2584 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2585 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002586 std::vector<spv::Id> constituents;
2587 for (int c = 0; c < (int)arguments.size(); ++c)
2588 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002589 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002590 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002591 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002592 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002593 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002594
2595 builder.clearAccessChain();
2596 builder.setAccessChainRValue(constructed);
2597
2598 return false;
2599 }
2600
2601 // These six are component-wise compares with component-wise results.
2602 // Forward on to createBinaryOperation(), requesting a vector result.
2603 case glslang::EOpLessThan:
2604 case glslang::EOpGreaterThan:
2605 case glslang::EOpLessThanEqual:
2606 case glslang::EOpGreaterThanEqual:
2607 case glslang::EOpVectorEqual:
2608 case glslang::EOpVectorNotEqual:
2609 {
2610 // Map the operation to a binary
2611 binOp = node->getOp();
2612 reduceComparison = false;
2613 switch (node->getOp()) {
2614 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2615 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2616 default: binOp = node->getOp(); break;
2617 }
2618
2619 break;
2620 }
2621 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002622 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002623 binOp = glslang::EOpMul;
2624 break;
2625 case glslang::EOpOuterProduct:
2626 // two vectors multiplied to make a matrix
2627 binOp = glslang::EOpOuterProduct;
2628 break;
2629 case glslang::EOpDot:
2630 {
qining25262b32016-05-06 17:25:16 -04002631 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002632 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002633 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002634 binOp = glslang::EOpMul;
2635 break;
2636 }
2637 case glslang::EOpMod:
2638 // when an aggregate, this is the floating-point mod built-in function,
2639 // which can be emitted by the one in createBinaryOperation()
2640 binOp = glslang::EOpMod;
2641 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002642
John Kessenich140f3df2015-06-26 16:58:36 -06002643 case glslang::EOpEmitVertex:
2644 case glslang::EOpEndPrimitive:
2645 case glslang::EOpBarrier:
2646 case glslang::EOpMemoryBarrier:
2647 case glslang::EOpMemoryBarrierAtomicCounter:
2648 case glslang::EOpMemoryBarrierBuffer:
2649 case glslang::EOpMemoryBarrierImage:
2650 case glslang::EOpMemoryBarrierShared:
2651 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002652 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002653 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002654 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002655 case glslang::EOpWorkgroupMemoryBarrier:
2656 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002657 case glslang::EOpSubgroupBarrier:
2658 case glslang::EOpSubgroupMemoryBarrier:
2659 case glslang::EOpSubgroupMemoryBarrierBuffer:
2660 case glslang::EOpSubgroupMemoryBarrierImage:
2661 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002662 noReturnValue = true;
2663 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2664 break;
2665
John Kessenich426394d2015-07-23 10:22:48 -06002666 case glslang::EOpAtomicAdd:
2667 case glslang::EOpAtomicMin:
2668 case glslang::EOpAtomicMax:
2669 case glslang::EOpAtomicAnd:
2670 case glslang::EOpAtomicOr:
2671 case glslang::EOpAtomicXor:
2672 case glslang::EOpAtomicExchange:
2673 case glslang::EOpAtomicCompSwap:
2674 atomic = true;
2675 break;
2676
John Kesseniche5eee8f2019-10-18 01:03:11 -06002677#ifndef GLSLANG_WEB
2678 case glslang::EOpAtomicStore:
2679 noReturnValue = true;
2680 // fallthrough
2681 case glslang::EOpAtomicLoad:
2682 atomic = true;
2683 break;
2684
John Kessenich0d0c6d32017-07-23 16:08:26 -06002685 case glslang::EOpAtomicCounterAdd:
2686 case glslang::EOpAtomicCounterSubtract:
2687 case glslang::EOpAtomicCounterMin:
2688 case glslang::EOpAtomicCounterMax:
2689 case glslang::EOpAtomicCounterAnd:
2690 case glslang::EOpAtomicCounterOr:
2691 case glslang::EOpAtomicCounterXor:
2692 case glslang::EOpAtomicCounterExchange:
2693 case glslang::EOpAtomicCounterCompSwap:
2694 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2695 builder.addCapability(spv::CapabilityAtomicStorageOps);
2696 atomic = true;
2697 break;
2698
Ian Romanickb3bd4022019-01-21 08:57:25 -08002699 case glslang::EOpAbsDifference:
2700 case glslang::EOpAddSaturate:
2701 case glslang::EOpSubSaturate:
2702 case glslang::EOpAverage:
2703 case glslang::EOpAverageRounded:
2704 case glslang::EOpMul32x16:
2705 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2706 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2707 binOp = node->getOp();
2708 break;
2709
Daniel Kochdb32b242020-03-17 20:42:47 -04002710 case glslang::EOpIgnoreIntersection:
2711 case glslang::EOpTerminateRay:
2712 case glslang::EOpTrace:
2713 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002714 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2715 noReturnValue = true;
2716 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002717 case glslang::EOpRayQueryInitialize:
2718 case glslang::EOpRayQueryTerminate:
2719 case glslang::EOpRayQueryGenerateIntersection:
2720 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002721 builder.addExtension("SPV_KHR_ray_query");
2722 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002723 noReturnValue = true;
2724 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002725 case glslang::EOpRayQueryProceed:
2726 case glslang::EOpRayQueryGetIntersectionType:
2727 case glslang::EOpRayQueryGetRayTMin:
2728 case glslang::EOpRayQueryGetRayFlags:
2729 case glslang::EOpRayQueryGetIntersectionT:
2730 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2731 case glslang::EOpRayQueryGetIntersectionInstanceId:
2732 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2733 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2734 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2735 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2736 case glslang::EOpRayQueryGetIntersectionFrontFace:
2737 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2738 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2739 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2740 case glslang::EOpRayQueryGetWorldRayDirection:
2741 case glslang::EOpRayQueryGetWorldRayOrigin:
2742 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2743 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2744 builder.addExtension("SPV_KHR_ray_query");
2745 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2746 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002747 case glslang::EOpCooperativeMatrixLoad:
2748 case glslang::EOpCooperativeMatrixStore:
2749 noReturnValue = true;
2750 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002751 case glslang::EOpBeginInvocationInterlock:
2752 case glslang::EOpEndInvocationInterlock:
2753 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2754 noReturnValue = true;
2755 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002756#endif
Chao Chen3c366992018-09-19 11:41:59 -07002757
Jeff Bolz04d73732019-05-31 13:06:01 -05002758 case glslang::EOpDebugPrintf:
2759 noReturnValue = true;
2760 break;
2761
John Kessenich140f3df2015-06-26 16:58:36 -06002762 default:
2763 break;
2764 }
2765
2766 //
2767 // See if it maps to a regular operation.
2768 //
John Kessenich140f3df2015-06-26 16:58:36 -06002769 if (binOp != glslang::EOpNull) {
2770 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2771 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2772 assert(left && right);
2773
2774 builder.clearAccessChain();
2775 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002776 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002777
2778 builder.clearAccessChain();
2779 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002780 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002781
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002782 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002783 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002784 TranslateNoContractionDecoration(node->getType().getQualifier()),
2785 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002786 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002787 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002788 left->getType().getBasicType(), reduceComparison);
2789
2790 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002791 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002792 builder.clearAccessChain();
2793 builder.setAccessChainRValue(result);
2794
2795 return false;
2796 }
2797
John Kessenich426394d2015-07-23 10:22:48 -06002798 //
2799 // Create the list of operands.
2800 //
John Kessenich140f3df2015-06-26 16:58:36 -06002801 glslang::TIntermSequence& glslangOperands = node->getSequence();
2802 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002803 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002804 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002805 // special case l-value operands; there are just a few
2806 bool lvalue = false;
2807 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002808 case glslang::EOpModf:
2809 if (arg == 1)
2810 lvalue = true;
2811 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002812
Torosdagli06c2eee2020-03-19 11:09:57 -04002813 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002814 case glslang::EOpRayQueryTerminate:
2815 case glslang::EOpRayQueryConfirmIntersection:
2816 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002817 case glslang::EOpRayQueryGenerateIntersection:
2818 case glslang::EOpRayQueryGetIntersectionType:
2819 case glslang::EOpRayQueryGetIntersectionT:
2820 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2821 case glslang::EOpRayQueryGetIntersectionInstanceId:
2822 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2823 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2824 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2825 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2826 case glslang::EOpRayQueryGetIntersectionFrontFace:
2827 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2828 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2829 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2830 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2831 if (arg == 0)
2832 lvalue = true;
2833 break;
2834
John Kesseniche5eee8f2019-10-18 01:03:11 -06002835 case glslang::EOpAtomicAdd:
2836 case glslang::EOpAtomicMin:
2837 case glslang::EOpAtomicMax:
2838 case glslang::EOpAtomicAnd:
2839 case glslang::EOpAtomicOr:
2840 case glslang::EOpAtomicXor:
2841 case glslang::EOpAtomicExchange:
2842 case glslang::EOpAtomicCompSwap:
2843 if (arg == 0)
2844 lvalue = true;
2845 break;
2846
John Kessenicha28f7a72019-08-06 07:00:58 -06002847#ifndef GLSLANG_WEB
2848 case glslang::EOpFrexp:
2849 if (arg == 1)
2850 lvalue = true;
2851 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002852 case glslang::EOpInterpolateAtSample:
2853 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002854 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002855 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002856 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002857
2858 // Does it need a swizzle inversion? If so, evaluation is inverted;
2859 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002860 // That is, we transform
2861 //
2862 // interpolate(v.zy) -> interpolate(v).zy
2863 //
John Kessenichecba76f2017-01-06 00:34:48 -07002864 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002865 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002866 invertedType = convertGlslangToSpvType(
2867 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002868 }
Rex Xu7a26c172015-12-08 17:12:09 +08002869 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002870 case glslang::EOpAtomicLoad:
2871 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002872 case glslang::EOpAtomicCounterAdd:
2873 case glslang::EOpAtomicCounterSubtract:
2874 case glslang::EOpAtomicCounterMin:
2875 case glslang::EOpAtomicCounterMax:
2876 case glslang::EOpAtomicCounterAnd:
2877 case glslang::EOpAtomicCounterOr:
2878 case glslang::EOpAtomicCounterXor:
2879 case glslang::EOpAtomicCounterExchange:
2880 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002881 if (arg == 0)
2882 lvalue = true;
2883 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002884 case glslang::EOpAddCarry:
2885 case glslang::EOpSubBorrow:
2886 if (arg == 2)
2887 lvalue = true;
2888 break;
2889 case glslang::EOpUMulExtended:
2890 case glslang::EOpIMulExtended:
2891 if (arg >= 2)
2892 lvalue = true;
2893 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002894 case glslang::EOpCooperativeMatrixLoad:
2895 if (arg == 0 || arg == 1)
2896 lvalue = true;
2897 break;
2898 case glslang::EOpCooperativeMatrixStore:
2899 if (arg == 1)
2900 lvalue = true;
2901 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002902#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002903 default:
2904 break;
2905 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002906 builder.clearAccessChain();
2907 if (invertedType != spv::NoType && arg == 0)
2908 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2909 else
2910 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002911
John Kessenichb9197c82019-08-11 07:41:45 -06002912#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002913 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2914 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2915
2916 if (arg == 1) {
2917 // fold "element" parameter into the access chain
2918 spv::Builder::AccessChain save = builder.getAccessChain();
2919 builder.clearAccessChain();
2920 glslangOperands[2]->traverse(this);
2921
2922 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2923
2924 builder.setAccessChain(save);
2925
2926 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002927 builder.accessChainPush(elementId,
2928 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2929 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002930
2931 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2932 unsigned int alignment = builder.getAccessChain().alignment;
2933
2934 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2935 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2936 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2937 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2938 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002939 if (builder.getStorageClass(builder.getAccessChain().base) ==
2940 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002941 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2942 }
2943
2944 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2945
2946 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2947 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2948 }
2949
John Kessenich8985fc92020-03-03 10:25:07 -07002950 if (memoryAccess &
2951 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2952 memoryAccessOperands.push_back(spv::IdImmediate(true,
2953 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002954 }
2955 } else if (arg == 2) {
2956 continue;
2957 }
2958 }
John Kessenichb9197c82019-08-11 07:41:45 -06002959#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002960
John Kessenichbbbd9a22020-03-03 07:21:37 -07002961 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002962 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002963 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2964 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2965 // reduce to a simple access chain. So, we need a temporary vector to
2966 // receive the result, and must later swizzle that into the original
2967 // l-value.
2968 complexLvalue = builder.getAccessChain();
John Kessenich8985fc92020-03-03 10:25:07 -07002969 temporaryLvalue = builder.createVariable(spv::StorageClassFunction,
2970 builder.accessChainGetInferredType(), "swizzleTemp");
John Kessenichbbbd9a22020-03-03 07:21:37 -07002971 operands.push_back(temporaryLvalue);
2972 } else {
2973 operands.push_back(builder.accessChainGetLValue());
2974 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002975 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2976 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2977 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002978 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002979 glslang::TOperator glslangOp = node->getOp();
2980 if (arg == 1 &&
2981 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
2982 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
2983 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
2984 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
2985 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
2986 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
2987 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
2988 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
2989 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
2990 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
2991 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
2992 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
2993 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
2994 )) {
2995 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
2996 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
2997 }
2998 else {
2999 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3000 }
3001
John Kesseniche485c7a2017-05-31 18:50:53 -06003002 }
John Kessenich140f3df2015-06-26 16:58:36 -06003003 }
John Kessenich426394d2015-07-23 10:22:48 -06003004
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003005 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003006#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003007 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3008 std::vector<spv::IdImmediate> idImmOps;
3009
3010 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3011 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3012 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3013 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3014 // get the pointee type
3015 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3016 assert(builder.isCooperativeMatrixType(typeId));
3017 // do the op
3018 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3019 // store the result to the pointer (out param 'm')
3020 builder.createStore(result, operands[0]);
3021 result = 0;
3022 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3023 std::vector<spv::IdImmediate> idImmOps;
3024
3025 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3026 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3027 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3028 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3029 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3030
3031 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3032 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003033 } else
3034#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003035 if (atomic) {
3036 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003037 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3038 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003039 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3040 if (!nonSemanticDebugPrintf) {
3041 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3042 }
3043 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3044 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003045 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003046 // Pass through to generic operations.
3047 switch (glslangOperands.size()) {
3048 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003049 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003050 break;
3051 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003052 {
3053 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003054 TranslateNoContractionDecoration(node->getType().getQualifier()),
3055 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003056 result = createUnaryOperation(
3057 node->getOp(), decorations,
3058 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003059 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003060 }
John Kessenich426394d2015-07-23 10:22:48 -06003061 break;
3062 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003063 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003064 break;
3065 }
John Kessenichbbbd9a22020-03-03 07:21:37 -07003066 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003067 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenichbbbd9a22020-03-03 07:21:37 -07003068 else if (temporaryLvalue != spv::NoResult) {
3069 builder.setAccessChain(complexLvalue);
3070 builder.accessChainStore(builder.createLoad(temporaryLvalue));
3071 }
John Kessenich140f3df2015-06-26 16:58:36 -06003072 }
3073
3074 if (noReturnValue)
3075 return false;
3076
3077 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003078 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003079 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003080 } else {
3081 builder.clearAccessChain();
3082 builder.setAccessChainRValue(result);
3083 return false;
3084 }
3085}
3086
John Kessenich433e9ff2017-01-26 20:31:11 -07003087// This path handles both if-then-else and ?:
3088// The if-then-else has a node type of void, while
3089// ?: has either a void or a non-void node type
3090//
3091// Leaving the result, when not void:
3092// GLSL only has r-values as the result of a :?, but
3093// if we have an l-value, that can be more efficient if it will
3094// become the base of a complex r-value expression, because the
3095// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003096bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3097{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003098 // see if OpSelect can handle it
3099 const auto isOpSelectable = [&]() {
3100 if (node->getBasicType() == glslang::EbtVoid)
3101 return false;
3102 // OpSelect can do all other types starting with SPV 1.4
3103 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3104 // pre-1.4, only scalars and vectors can be handled
3105 if ((!node->getType().isScalar() && !node->getType().isVector()))
3106 return false;
3107 }
3108 return true;
3109 };
3110
John Kessenich4bee5312018-02-20 21:29:05 -07003111 // See if it simple and safe, or required, to execute both sides.
3112 // Crucially, side effects must be either semantically required or avoided,
3113 // and there are performance trade-offs.
3114 // Return true if required or a good idea (and safe) to execute both sides,
3115 // false otherwise.
3116 const auto bothSidesPolicy = [&]() -> bool {
3117 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003118 if (node->getTrueBlock() == nullptr ||
3119 node->getFalseBlock() == nullptr)
3120 return false;
3121
John Kessenich4bee5312018-02-20 21:29:05 -07003122 // required? (unless we write additional code to look for side effects
3123 // and make performance trade-offs if none are present)
3124 if (!node->getShortCircuit())
3125 return true;
3126
3127 // if not required to execute both, decide based on performance/practicality...
3128
John Kessenich0c1e71a2019-01-10 18:23:06 +07003129 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003130 return false;
3131
John Kessenich433e9ff2017-01-26 20:31:11 -07003132 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3133 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3134
3135 // return true if a single operand to ? : is okay for OpSelect
3136 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003137 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003138 };
3139
3140 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3141 operandOkay(node->getFalseBlock()->getAsTyped());
3142 };
3143
John Kessenich4bee5312018-02-20 21:29:05 -07003144 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3145 // emit the condition before doing anything with selection
3146 node->getCondition()->traverse(this);
3147 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3148
3149 // Find a way of executing both sides and selecting the right result.
3150 const auto executeBothSides = [&]() -> void {
3151 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003152 node->getTrueBlock()->traverse(this);
3153 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3154 node->getFalseBlock()->traverse(this);
3155 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3156
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003157 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003158
John Kessenich4bee5312018-02-20 21:29:05 -07003159 // done if void
3160 if (node->getBasicType() == glslang::EbtVoid)
3161 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003162
John Kessenich4bee5312018-02-20 21:29:05 -07003163 // emit code to select between trueValue and falseValue
3164
3165 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003166 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003167 // Emit OpSelect for this selection.
3168
3169 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003170 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3171 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003172 condition = builder.smearScalar(spv::NoPrecision, condition,
3173 builder.makeVectorType(builder.makeBoolType(),
3174 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003175 }
John Kessenich4bee5312018-02-20 21:29:05 -07003176
3177 // OpSelect
3178 result = builder.createTriOp(spv::OpSelect,
3179 convertGlslangToSpvType(node->getType()), condition,
3180 trueValue, falseValue);
3181
3182 builder.clearAccessChain();
3183 builder.setAccessChainRValue(result);
3184 } else {
3185 // We need control flow to select the result.
3186 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3187 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3188
3189 // Selection control:
3190 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3191
3192 // make an "if" based on the value created by the condition
3193 spv::Builder::If ifBuilder(condition, control, builder);
3194
3195 // emit the "then" statement
3196 builder.createStore(trueValue, result);
3197 ifBuilder.makeBeginElse();
3198 // emit the "else" statement
3199 builder.createStore(falseValue, result);
3200
3201 // finish off the control flow
3202 ifBuilder.makeEndIf();
3203
3204 builder.clearAccessChain();
3205 builder.setAccessChainLValue(result);
3206 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003207 };
3208
John Kessenich4bee5312018-02-20 21:29:05 -07003209 // Execute the one side needed, as per the condition
3210 const auto executeOneSide = [&]() {
3211 // Always emit control flow.
3212 if (node->getBasicType() != glslang::EbtVoid)
3213 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003214
John Kessenich4bee5312018-02-20 21:29:05 -07003215 // Selection control:
3216 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3217
3218 // make an "if" based on the value created by the condition
3219 spv::Builder::If ifBuilder(condition, control, builder);
3220
3221 // emit the "then" statement
3222 if (node->getTrueBlock() != nullptr) {
3223 node->getTrueBlock()->traverse(this);
3224 if (result != spv::NoResult)
3225 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3226 }
3227
3228 if (node->getFalseBlock() != nullptr) {
3229 ifBuilder.makeBeginElse();
3230 // emit the "else" statement
3231 node->getFalseBlock()->traverse(this);
3232 if (result != spv::NoResult)
3233 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3234 }
3235
3236 // finish off the control flow
3237 ifBuilder.makeEndIf();
3238
3239 if (result != spv::NoResult) {
3240 builder.clearAccessChain();
3241 builder.setAccessChainLValue(result);
3242 }
3243 };
3244
3245 // Try for OpSelect (or a requirement to execute both sides)
3246 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003247 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3248 if (node->getType().getQualifier().isSpecConstant())
3249 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003250 executeBothSides();
3251 } else
3252 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003253
3254 return false;
3255}
3256
3257bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3258{
3259 // emit and get the condition before doing anything with switch
3260 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003261 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003262
Rex Xu57e65922017-07-04 23:23:40 +08003263 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003264 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003265
John Kessenich140f3df2015-06-26 16:58:36 -06003266 // browse the children to sort out code segments
3267 int defaultSegment = -1;
3268 std::vector<TIntermNode*> codeSegments;
3269 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3270 std::vector<int> caseValues;
3271 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3272 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3273 TIntermNode* child = *c;
3274 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003275 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003276 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003277 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003278 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3279 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003280 } else
3281 codeSegments.push_back(child);
3282 }
3283
qining25262b32016-05-06 17:25:16 -04003284 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003285 // statements between the last case and the end of the switch statement
3286 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3287 (int)codeSegments.size() == defaultSegment)
3288 codeSegments.push_back(nullptr);
3289
3290 // make the switch statement
3291 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003292 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3293 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003294
3295 // emit all the code in the segments
3296 breakForLoop.push(false);
3297 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3298 builder.nextSwitchSegment(segmentBlocks, s);
3299 if (codeSegments[s])
3300 codeSegments[s]->traverse(this);
3301 else
3302 builder.addSwitchBreak();
3303 }
3304 breakForLoop.pop();
3305
3306 builder.endSwitch(segmentBlocks);
3307
3308 return false;
3309}
3310
3311void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3312{
3313 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003314 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003315
3316 builder.clearAccessChain();
3317 builder.setAccessChainRValue(constant);
3318}
3319
3320bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3321{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003322 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003323 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003324
3325 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003326 std::vector<unsigned int> operands;
3327 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003328
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003329 // Spec requires back edges to target header blocks, and every header block
3330 // must dominate its merge block. Make a header block first to ensure these
3331 // conditions are met. By definition, it will contain OpLoopMerge, followed
3332 // by a block-ending branch. But we don't want to put any other body/test
3333 // instructions in it, since the body/test may have arbitrary instructions,
3334 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003335 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003336 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003337 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003338 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003339 spv::Block& test = builder.makeNewBlock();
3340 builder.createBranch(&test);
3341
3342 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003343 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003344 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003345 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3346
3347 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003348 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003349 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003350 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003351 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003352 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003353
3354 builder.setBuildPoint(&blocks.continue_target);
3355 if (node->getTerminal())
3356 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003357 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003358 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003359 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003360 builder.createBranch(&blocks.body);
3361
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003362 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003363 builder.setBuildPoint(&blocks.body);
3364 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003365 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003366 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003367 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003368
3369 builder.setBuildPoint(&blocks.continue_target);
3370 if (node->getTerminal())
3371 node->getTerminal()->traverse(this);
3372 if (node->getTest()) {
3373 node->getTest()->traverse(this);
3374 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003375 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003376 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003377 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003378 // TODO: unless there was a break/return/discard instruction
3379 // somewhere in the body, this is an infinite loop, so we should
3380 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003381 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003382 }
John Kessenich140f3df2015-06-26 16:58:36 -06003383 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003384 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003385 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003386 return false;
3387}
3388
3389bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3390{
3391 if (node->getExpression())
3392 node->getExpression()->traverse(this);
3393
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003394 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003395
John Kessenich140f3df2015-06-26 16:58:36 -06003396 switch (node->getFlowOp()) {
3397 case glslang::EOpKill:
3398 builder.makeDiscard();
3399 break;
3400 case glslang::EOpBreak:
3401 if (breakForLoop.top())
3402 builder.createLoopExit();
3403 else
3404 builder.addSwitchBreak();
3405 break;
3406 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003407 builder.createLoopContinue();
3408 break;
3409 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003410 if (node->getExpression()) {
3411 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3412 spv::Id returnId = accessChainLoad(glslangReturnType);
3413 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3414 builder.clearAccessChain();
3415 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3416 builder.setAccessChainLValue(copyId);
3417 multiTypeStore(glslangReturnType, returnId);
3418 returnId = builder.createLoad(copyId);
3419 }
3420 builder.makeReturn(false, returnId);
3421 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003422 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003423
3424 builder.clearAccessChain();
3425 break;
3426
John Kessenichb9197c82019-08-11 07:41:45 -06003427#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003428 case glslang::EOpDemote:
3429 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3430 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3431 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3432 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003433#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003434
John Kessenich140f3df2015-06-26 16:58:36 -06003435 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003436 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003437 break;
3438 }
3439
3440 return false;
3441}
3442
John Kessenich9c14f772019-06-17 08:38:35 -06003443spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003444{
qining25262b32016-05-06 17:25:16 -04003445 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003446 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003447 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003448 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003449 spv::Id result = createSpvConstant(*node);
3450 if (result != spv::NoResult)
3451 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003452 }
3453
3454 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003455 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003456 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3457 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003458
John Kessenichb9197c82019-08-11 07:41:45 -06003459 const bool contains16BitType = node->getType().contains16BitFloat() ||
3460 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003461 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003462 switch (storageClass) {
3463 case spv::StorageClassInput:
3464 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003465 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003466 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003467 break;
John Kessenich18310872018-05-14 22:08:53 -06003468 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003469 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003470 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3471 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003472 else
3473 builder.addCapability(spv::CapabilityStorageUniform16);
3474 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003475#ifndef GLSLANG_WEB
3476 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003477 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003478 builder.addCapability(spv::CapabilityStoragePushConstant16);
3479 break;
John Kessenich18310872018-05-14 22:08:53 -06003480 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003481 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003482 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003483 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3484 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003485#endif
John Kessenich18310872018-05-14 22:08:53 -06003486 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003487 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003488 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003489 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003490 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003491 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003492 }
3493 }
Rex Xuf89ad982017-04-07 23:22:33 +08003494
John Kessenichb9197c82019-08-11 07:41:45 -06003495 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003496 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003497 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003498 builder.addCapability(spv::CapabilityStoragePushConstant8);
3499 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003500 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003501 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003502 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003503 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003504 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003505 } else {
3506 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003507 }
3508 }
3509
John Kessenich140f3df2015-06-26 16:58:36 -06003510 const char* name = node->getName().c_str();
3511 if (glslang::IsAnonymous(name))
3512 name = "";
3513
3514 return builder.createVariable(storageClass, spvType, name);
3515}
3516
3517// Return type Id of the sampled type.
3518spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3519{
3520 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003521 case glslang::EbtInt: return builder.makeIntType(32);
3522 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003523 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003524#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003525 case glslang::EbtFloat16:
3526 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3527 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3528 return builder.makeFloatType(16);
3529#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003530 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003531 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003532 return builder.makeFloatType(32);
3533 }
3534}
3535
John Kessenich8c8505c2016-07-26 12:50:38 -06003536// If node is a swizzle operation, return the type that should be used if
3537// the swizzle base is first consumed by another operation, before the swizzle
3538// is applied.
3539spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3540{
John Kessenichecba76f2017-01-06 00:34:48 -07003541 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003542 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3543 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3544 else
3545 return spv::NoType;
3546}
3547
3548// When inverting a swizzle with a parent op, this function
3549// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003550spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3551 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003552{
3553 std::vector<unsigned> swizzle;
3554 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3555 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3556}
3557
John Kessenich8c8505c2016-07-26 12:50:38 -06003558// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3559void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3560{
3561 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3562 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3563 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3564}
3565
John Kessenich3ac051e2015-12-20 11:29:16 -07003566// Convert from a glslang type to an SPV type, by calling into a
3567// recursive version of this function. This establishes the inherited
3568// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003569spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003570{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003571 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003572}
3573
3574// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003575// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003576// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003577spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003578 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3579 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003580{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003581 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003582
3583 switch (type.getBasicType()) {
3584 case glslang::EbtVoid:
3585 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003586 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003587 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003588 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003589 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3590 // a 32-bit int where non-0 means true.
3591 if (explicitLayout != glslang::ElpNone)
3592 spvType = builder.makeUintType(32);
3593 else
3594 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003595 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003596 case glslang::EbtInt:
3597 spvType = builder.makeIntType(32);
3598 break;
3599 case glslang::EbtUint:
3600 spvType = builder.makeUintType(32);
3601 break;
3602 case glslang::EbtFloat:
3603 spvType = builder.makeFloatType(32);
3604 break;
3605#ifndef GLSLANG_WEB
3606 case glslang::EbtDouble:
3607 spvType = builder.makeFloatType(64);
3608 break;
3609 case glslang::EbtFloat16:
3610 spvType = builder.makeFloatType(16);
3611 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003612 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003613 spvType = builder.makeIntType(8);
3614 break;
3615 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003616 spvType = builder.makeUintType(8);
3617 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003618 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003619 spvType = builder.makeIntType(16);
3620 break;
3621 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003622 spvType = builder.makeUintType(16);
3623 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003624 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003625 spvType = builder.makeIntType(64);
3626 break;
3627 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003628 spvType = builder.makeUintType(64);
3629 break;
John Kessenich426394d2015-07-23 10:22:48 -06003630 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003631 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003632 spvType = builder.makeUintType(32);
3633 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003634 case glslang::EbtAccStruct:
3635 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003636 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003637 case glslang::EbtRayQuery:
3638 spvType = builder.makeRayQueryType();
3639 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003640 case glslang::EbtReference:
3641 {
3642 // Make the forward pointer, then recurse to convert the structure type, then
3643 // patch up the forward pointer with a real pointer type.
3644 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3645 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3646 forwardPointers[type.getReferentType()] = forwardId;
3647 }
3648 spvType = forwardPointers[type.getReferentType()];
3649 if (!forwardReferenceOnly) {
3650 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3651 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3652 forwardPointers[type.getReferentType()],
3653 referentType);
3654 }
3655 }
3656 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003657#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003658 case glslang::EbtSampler:
3659 {
3660 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003661 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003662 spvType = builder.makeSamplerType();
3663 } else {
3664 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003665 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3666 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3667 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3668 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003669 // already has both image and sampler, make the combined type
3670 spvType = builder.makeSampledImageType(spvType);
3671 }
John Kessenich55e7d112015-11-15 21:33:39 -07003672 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003673 }
John Kessenich140f3df2015-06-26 16:58:36 -06003674 break;
3675 case glslang::EbtStruct:
3676 case glslang::EbtBlock:
3677 {
3678 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003679 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003680
3681 // Try to share structs for different layouts, but not yet for other
3682 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003683 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003684 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003685 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003686 break;
3687
3688 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003689 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003690 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003691 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003692 }
3693 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003694 case glslang::EbtString:
3695 // no type used for OpString
3696 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003697 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003698 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003699 break;
3700 }
3701
3702 if (type.isMatrix())
3703 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3704 else {
3705 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3706 if (type.getVectorSize() > 1)
3707 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3708 }
3709
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003710 if (type.isCoopMat()) {
3711 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3712 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3713 if (type.getBasicType() == glslang::EbtFloat16)
3714 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003715 if (type.getBasicType() == glslang::EbtUint8 ||
3716 type.getBasicType() == glslang::EbtInt8) {
3717 builder.addCapability(spv::CapabilityInt8);
3718 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003719
3720 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3721 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3722 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3723
3724 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3725 }
3726
John Kessenich140f3df2015-06-26 16:58:36 -06003727 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003728 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3729
John Kessenichc9a80832015-09-12 12:17:44 -06003730 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003731 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003732 // We need to decorate array strides for types needing explicit layout, except blocks.
3733 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003734 // Use a dummy glslang type for querying internal strides of
3735 // arrays of arrays, but using just a one-dimensional array.
3736 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003737 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3738 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003739
3740 // Will compute the higher-order strides here, rather than making a whole
3741 // pile of types and doing repetitive recursion on their contents.
3742 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3743 }
John Kessenichf8842e52016-01-04 19:22:56 -07003744
3745 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003746 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003747 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003748 if (stride > 0)
3749 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003750 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003751 }
3752 } else {
3753 // single-dimensional array, and don't yet have stride
3754
John Kessenichf8842e52016-01-04 19:22:56 -07003755 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003756 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3757 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003758 }
John Kessenich31ed4832015-09-09 17:51:38 -06003759
John Kessenichead86222018-03-28 18:01:20 -06003760 // Do the outer dimension, which might not be known for a runtime-sized array.
3761 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3762 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003763 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003764 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003765#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003766 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003767 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003768 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3769 }
John Kessenichb9197c82019-08-11 07:41:45 -06003770#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003771 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003772 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003773 if (stride > 0)
3774 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003775 }
3776
3777 return spvType;
3778}
3779
John Kessenich0e737842017-03-24 18:38:16 -06003780// TODO: this functionality should exist at a higher level, in creating the AST
3781//
3782// Identify interface members that don't have their required extension turned on.
3783//
3784bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3785{
John Kessenicha28f7a72019-08-06 07:00:58 -06003786#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003787 auto& extensions = glslangIntermediate->getRequestedExtensions();
3788
Rex Xubcf291a2017-03-29 23:01:36 +08003789 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3790 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3791 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003792 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3793 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3794 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003795
3796 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3797 if (member.getFieldName() == "gl_ViewportMask" &&
3798 extensions.find("GL_NV_viewport_array2") == extensions.end())
3799 return true;
3800 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3801 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3802 return true;
3803 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3804 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3805 return true;
3806 }
3807#endif
John Kessenich0e737842017-03-24 18:38:16 -06003808
3809 return false;
3810};
3811
John Kessenich6090df02016-06-30 21:18:02 -06003812// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3813// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3814// Mutually recursive with convertGlslangToSpvType().
3815spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3816 const glslang::TTypeList* glslangMembers,
3817 glslang::TLayoutPacking explicitLayout,
3818 const glslang::TQualifier& qualifier)
3819{
3820 // Create a vector of struct types for SPIR-V to consume
3821 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003822 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3823 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003824 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003825 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3826 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3827 if (glslangMember.hiddenMember()) {
3828 ++memberDelta;
3829 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003830 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003831 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003832 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003833 if (filterMember(glslangMember)) {
3834 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003835 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003836 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003837 }
Roy05a5b532020-01-03 16:21:34 +08003838 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003839 }
John Kessenich6090df02016-06-30 21:18:02 -06003840 // modify just this child's view of the qualifier
3841 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3842 InheritQualifiers(memberQualifier, qualifier);
3843
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003844 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003845 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003846 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003847
3848 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003849 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3850 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003851
3852 // Make forward pointers for any pointer members, and create a list of members to
3853 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003854 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003855 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3856 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3857 }
3858 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003859 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3860 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003861 } else {
3862 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003863 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3864 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003865 }
John Kessenich6090df02016-06-30 21:18:02 -06003866 }
3867 }
3868
3869 // Make the SPIR-V type
3870 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003871 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003872 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3873
3874 // Decorate it
3875 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3876
John Kessenichd72f4882019-01-16 14:55:37 +07003877 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003878 auto it = deferredForwardPointers[i];
3879 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3880 }
3881
John Kessenich6090df02016-06-30 21:18:02 -06003882 return spvType;
3883}
3884
3885void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3886 const glslang::TTypeList* glslangMembers,
3887 glslang::TLayoutPacking explicitLayout,
3888 const glslang::TQualifier& qualifier,
3889 spv::Id spvType)
3890{
3891 // Name and decorate the non-hidden members
3892 int offset = -1;
3893 int locationOffset = 0; // for use within the members of this struct
3894 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3895 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3896 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003897 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003898 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003899 if (filterMember(glslangMember))
3900 continue;
3901 }
John Kessenich6090df02016-06-30 21:18:02 -06003902
3903 // modify just this child's view of the qualifier
3904 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3905 InheritQualifiers(memberQualifier, qualifier);
3906
3907 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003908 if (member < 0)
3909 continue;
3910
3911 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3912 builder.addMemberDecoration(spvType, member,
3913 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3914 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3915 // Add interpolation and auxiliary storage decorations only to
3916 // top-level members of Input and Output storage classes
3917 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3918 type.getQualifier().storage == glslang::EvqVaryingOut) {
3919 if (type.getBasicType() == glslang::EbtBlock ||
3920 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3921 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3922 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003923#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003924 addMeshNVDecoration(spvType, member, memberQualifier);
3925#endif
John Kessenich6090df02016-06-30 21:18:02 -06003926 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003927 }
3928 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003929
John Kessenichb9197c82019-08-11 07:41:45 -06003930#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003931 if (type.getBasicType() == glslang::EbtBlock &&
3932 qualifier.storage == glslang::EvqBuffer) {
3933 // Add memory decorations only to top-level members of shader storage block
3934 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003935 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003936 for (unsigned int i = 0; i < memory.size(); ++i)
3937 builder.addMemberDecoration(spvType, member, memory[i]);
3938 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003939
John Kessenichb9197c82019-08-11 07:41:45 -06003940#endif
John Kessenich6090df02016-06-30 21:18:02 -06003941
John Kessenich5d610ee2018-03-07 18:05:55 -07003942 // Location assignment was already completed correctly by the front end,
3943 // just track whether a member needs to be decorated.
3944 // Ignore member locations if the container is an array, as that's
3945 // ill-specified and decisions have been made to not allow this.
3946 if (! type.isArray() && memberQualifier.hasLocation())
3947 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003948
John Kessenich5d610ee2018-03-07 18:05:55 -07003949 if (qualifier.hasLocation()) // track for upcoming inheritance
3950 locationOffset += glslangIntermediate->computeTypeLocationSize(
3951 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003952
John Kessenich5d610ee2018-03-07 18:05:55 -07003953 // component, XFB, others
3954 if (glslangMember.getQualifier().hasComponent())
3955 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3956 glslangMember.getQualifier().layoutComponent);
3957 if (glslangMember.getQualifier().hasXfbOffset())
3958 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3959 glslangMember.getQualifier().layoutXfbOffset);
3960 else if (explicitLayout != glslang::ElpNone) {
3961 // figure out what to do with offset, which is accumulating
3962 int nextOffset;
3963 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3964 if (offset >= 0)
3965 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3966 offset = nextOffset;
3967 }
John Kessenich6090df02016-06-30 21:18:02 -06003968
John Kessenich5d610ee2018-03-07 18:05:55 -07003969 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3970 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3971 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003972
John Kessenich5d610ee2018-03-07 18:05:55 -07003973 // built-in variable decorations
3974 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3975 if (builtIn != spv::BuiltInMax)
3976 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003977
John Kessenichb9197c82019-08-11 07:41:45 -06003978#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003979 // nonuniform
3980 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3981
John Kessenichead86222018-03-28 18:01:20 -06003982 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3983 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3984 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3985 memberQualifier.semanticName);
3986 }
3987
John Kessenich5d610ee2018-03-07 18:05:55 -07003988 if (builtIn == spv::BuiltInLayer) {
3989 // SPV_NV_viewport_array2 extension
3990 if (glslangMember.getQualifier().layoutViewportRelative){
3991 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3992 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3993 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003994 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003995 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3996 builder.addMemberDecoration(spvType, member,
3997 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3998 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3999 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4000 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004001 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004002 }
4003 if (glslangMember.getQualifier().layoutPassthrough) {
4004 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4005 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4006 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4007 }
chaoc771d89f2017-01-13 01:10:53 -08004008#endif
John Kessenich6090df02016-06-30 21:18:02 -06004009 }
4010
4011 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004012 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4013 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004014}
4015
John Kessenich6c292d32016-02-15 20:58:50 -07004016// Turn the expression forming the array size into an id.
4017// This is not quite trivial, because of specialization constants.
4018// Sometimes, a raw constant is turned into an Id, and sometimes
4019// a specialization constant expression is.
4020spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4021{
4022 // First, see if this is sized with a node, meaning a specialization constant:
4023 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4024 if (specNode != nullptr) {
4025 builder.clearAccessChain();
4026 specNode->traverse(this);
4027 return accessChainLoad(specNode->getAsTyped()->getType());
4028 }
qining25262b32016-05-06 17:25:16 -04004029
John Kessenich6c292d32016-02-15 20:58:50 -07004030 // Otherwise, need a compile-time (front end) size, get it:
4031 int size = arraySizes.getDimSize(dim);
4032 assert(size > 0);
4033 return builder.makeUintConstant(size);
4034}
4035
John Kessenich103bef92016-02-08 21:38:15 -07004036// Wrap the builder's accessChainLoad to:
4037// - localize handling of RelaxedPrecision
4038// - use the SPIR-V inferred type instead of another conversion of the glslang type
4039// (avoids unnecessary work and possible type punning for structures)
4040// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004041spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4042{
John Kessenich103bef92016-02-08 21:38:15 -07004043 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004044
4045 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4046 coherentFlags |= TranslateCoherent(type);
4047
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004048 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004049 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004050
John Kessenich5611c6d2018-04-05 11:25:02 -06004051 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004052 TranslateNonUniformDecoration(type.getQualifier()),
4053 nominalTypeId,
4054 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4055 TranslateMemoryScope(coherentFlags),
4056 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004057
4058 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004059 if (type.getBasicType() == glslang::EbtBool) {
4060 if (builder.isScalarType(nominalTypeId)) {
4061 // Conversion for bool
4062 spv::Id boolType = builder.makeBoolType();
4063 if (nominalTypeId != boolType)
4064 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4065 } else if (builder.isVectorType(nominalTypeId)) {
4066 // Conversion for bvec
4067 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4068 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4069 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004070 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4071 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004072 }
4073 }
John Kessenich103bef92016-02-08 21:38:15 -07004074
4075 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004076}
4077
Rex Xu27253232016-02-23 17:51:09 +08004078// Wrap the builder's accessChainStore to:
4079// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004080//
4081// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004082void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4083{
4084 // Need to convert to abstract types when necessary
4085 if (type.getBasicType() == glslang::EbtBool) {
4086 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4087
4088 if (builder.isScalarType(nominalTypeId)) {
4089 // Conversion for bool
4090 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004091 if (nominalTypeId != boolType) {
4092 // keep these outside arguments, for determinant order-of-evaluation
4093 spv::Id one = builder.makeUintConstant(1);
4094 spv::Id zero = builder.makeUintConstant(0);
4095 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4096 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004097 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004098 } else if (builder.isVectorType(nominalTypeId)) {
4099 // Conversion for bvec
4100 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4101 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004102 if (nominalTypeId != bvecType) {
4103 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004104 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4105 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4106 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004107 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004108 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4109 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004110 }
4111 }
4112
Jeff Bolz36831c92018-09-05 10:11:41 -05004113 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4114 coherentFlags |= TranslateCoherent(type);
4115
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004116 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004117 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004118
Jeff Bolz36831c92018-09-05 10:11:41 -05004119 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004120 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4121 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004122 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004123}
4124
John Kessenich4bf71552016-09-02 11:20:21 -06004125// For storing when types match at the glslang level, but not might match at the
4126// SPIR-V level.
4127//
4128// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004129// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004130// as in a member-decorated way.
4131//
4132// NOTE: This function can handle any store request; if it's not special it
4133// simplifies to a simple OpStore.
4134//
4135// Implicitly uses the existing builder.accessChain as the storage target.
4136void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4137{
John Kessenichb3e24e42016-09-11 12:33:43 -06004138 // we only do the complex path here if it's an aggregate
4139 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004140 accessChainStore(type, rValue);
4141 return;
4142 }
4143
John Kessenichb3e24e42016-09-11 12:33:43 -06004144 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004145 spv::Id rType = builder.getTypeId(rValue);
4146 spv::Id lValue = builder.accessChainGetLValue();
4147 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4148 if (lType == rType) {
4149 accessChainStore(type, rValue);
4150 return;
4151 }
4152
John Kessenichb3e24e42016-09-11 12:33:43 -06004153 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004154 // where the two types were the same type in GLSL. This requires member
4155 // by member copy, recursively.
4156
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004157 // SPIR-V 1.4 added an instruction to do help do this.
4158 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4159 // However, bool in uniform space is changed to int, so
4160 // OpCopyLogical does not work for that.
4161 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4162 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4163 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4164 if (lBool == rBool) {
4165 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4166 accessChainStore(type, logicalCopy);
4167 return;
4168 }
4169 }
4170
John Kessenichb3e24e42016-09-11 12:33:43 -06004171 // If an array, copy element by element.
4172 if (type.isArray()) {
4173 glslang::TType glslangElementType(type, 0);
4174 spv::Id elementRType = builder.getContainedTypeId(rType);
4175 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4176 // get the source member
4177 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004178
John Kessenichb3e24e42016-09-11 12:33:43 -06004179 // set up the target storage
4180 builder.clearAccessChain();
4181 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004182 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4183 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004184
John Kessenichb3e24e42016-09-11 12:33:43 -06004185 // store the member
4186 multiTypeStore(glslangElementType, elementRValue);
4187 }
4188 } else {
4189 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004190
John Kessenichb3e24e42016-09-11 12:33:43 -06004191 // loop over structure members
4192 const glslang::TTypeList& members = *type.getStruct();
4193 for (int m = 0; m < (int)members.size(); ++m) {
4194 const glslang::TType& glslangMemberType = *members[m].type;
4195
4196 // get the source member
4197 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4198 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4199
4200 // set up the target storage
4201 builder.clearAccessChain();
4202 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004203 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4204 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004205
4206 // store the member
4207 multiTypeStore(glslangMemberType, memberRValue);
4208 }
John Kessenich4bf71552016-09-02 11:20:21 -06004209 }
4210}
4211
John Kessenichf85e8062015-12-19 13:57:10 -07004212// Decide whether or not this type should be
4213// decorated with offsets and strides, and if so
4214// whether std140 or std430 rules should be applied.
4215glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004216{
John Kessenichf85e8062015-12-19 13:57:10 -07004217 // has to be a block
4218 if (type.getBasicType() != glslang::EbtBlock)
4219 return glslang::ElpNone;
4220
Chao Chen3c366992018-09-19 11:41:59 -07004221 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004222 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004223 type.getQualifier().storage != glslang::EvqBuffer &&
4224 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004225 return glslang::ElpNone;
4226
4227 // return the layout to use
4228 switch (type.getQualifier().layoutPacking) {
4229 case glslang::ElpStd140:
4230 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004231 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004232 return type.getQualifier().layoutPacking;
4233 default:
4234 return glslang::ElpNone;
4235 }
John Kessenich31ed4832015-09-09 17:51:38 -06004236}
4237
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004238// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004239int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4240 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004241{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004242 int size;
John Kessenich49987892015-12-29 17:11:44 -07004243 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004244 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4245 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004246
4247 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004248}
4249
John Kessenich49987892015-12-29 17:11:44 -07004250// 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 -07004251// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004252int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4253 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004254{
John Kessenich49987892015-12-29 17:11:44 -07004255 glslang::TType elementType;
4256 elementType.shallowCopy(matrixType);
4257 elementType.clearArraySizes();
4258
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004259 int size;
John Kessenich49987892015-12-29 17:11:44 -07004260 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004261 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4262 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004263
4264 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004265}
4266
John Kessenich5e4b1242015-08-06 22:53:06 -06004267// Given a member type of a struct, realign the current offset for it, and compute
4268// the next (not yet aligned) offset for the next member, which will get aligned
4269// on the next call.
4270// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4271// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4272// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004273void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4274 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004275{
4276 // this will get a positive value when deemed necessary
4277 nextOffset = -1;
4278
John Kessenich5e4b1242015-08-06 22:53:06 -06004279 // override anything in currentOffset with user-set offset
4280 if (memberType.getQualifier().hasOffset())
4281 currentOffset = memberType.getQualifier().layoutOffset;
4282
4283 // It could be that current linker usage in glslang updated all the layoutOffset,
4284 // in which case the following code does not matter. But, that's not quite right
4285 // once cross-compilation unit GLSL validation is done, as the original user
4286 // settings are needed in layoutOffset, and then the following will come into play.
4287
John Kessenichf85e8062015-12-19 13:57:10 -07004288 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004289 if (! memberType.getQualifier().hasOffset())
4290 currentOffset = -1;
4291
4292 return;
4293 }
4294
John Kessenichf85e8062015-12-19 13:57:10 -07004295 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004296 if (currentOffset < 0)
4297 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004298
John Kessenich5e4b1242015-08-06 22:53:06 -06004299 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4300 // but possibly not yet correctly aligned.
4301
4302 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004303 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004304 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4305 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004306
4307 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004308 // TODO: make this consistent in early phases of code:
4309 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4310 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4311 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004312 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004313 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004314 int dummySize;
4315 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4316 if (componentAlignment <= 4)
4317 memberAlignment = componentAlignment;
4318 }
4319
4320 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004321 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004322
4323 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004324 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4325 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004326 glslang::RoundToPow2(currentOffset, 16);
4327
John Kessenich5e4b1242015-08-06 22:53:06 -06004328 nextOffset = currentOffset + memberSize;
4329}
4330
David Netoa901ffe2016-06-08 14:11:40 +01004331void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004332{
David Netoa901ffe2016-06-08 14:11:40 +01004333 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4334 switch (glslangBuiltIn)
4335 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004336 case glslang::EbvPointSize:
4337#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004338 case glslang::EbvClipDistance:
4339 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004340 case glslang::EbvViewportMaskNV:
4341 case glslang::EbvSecondaryPositionNV:
4342 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004343 case glslang::EbvPositionPerViewNV:
4344 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004345 case glslang::EbvTaskCountNV:
4346 case glslang::EbvPrimitiveCountNV:
4347 case glslang::EbvPrimitiveIndicesNV:
4348 case glslang::EbvClipDistancePerViewNV:
4349 case glslang::EbvCullDistancePerViewNV:
4350 case glslang::EbvLayerPerViewNV:
4351 case glslang::EbvMeshViewCountNV:
4352 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004353#endif
David Netoa901ffe2016-06-08 14:11:40 +01004354 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4355 // Alternately, we could just call this for any glslang built-in, since the
4356 // capability already guards against duplicates.
4357 TranslateBuiltInDecoration(glslangBuiltIn, false);
4358 break;
4359 default:
4360 // Capabilities were already generated when the struct was declared.
4361 break;
4362 }
John Kessenichebb50532016-05-16 19:22:05 -06004363}
4364
John Kessenich6fccb3c2016-09-19 16:01:41 -06004365bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004366{
John Kessenicheee9d532016-09-19 18:09:30 -06004367 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004368}
4369
John Kessenichd41993d2017-09-10 15:21:05 -06004370// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004371// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4372// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004373bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004374{
John Kessenich6a14f782017-12-04 02:48:10 -07004375 assert(qualifier == glslang::EvqIn ||
4376 qualifier == glslang::EvqOut ||
4377 qualifier == glslang::EvqInOut ||
4378 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004379 return qualifier != glslang::EvqConstReadOnly;
4380}
4381
4382// Is parameter pass-by-original?
4383bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4384 bool implicitThisParam)
4385{
4386 if (implicitThisParam) // implicit this
4387 return true;
4388 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004389 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004390 return paramType.containsOpaque() || // sampler, etc.
4391 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4392}
4393
John Kessenich140f3df2015-06-26 16:58:36 -06004394// Make all the functions, skeletally, without actually visiting their bodies.
4395void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4396{
John Kessenich8985fc92020-03-03 10:25:07 -07004397 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4398 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004399 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4400 if (paramPrecision != spv::NoPrecision)
4401 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004402 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004403 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004404 // Original and non-writable params pass the pointer directly and
4405 // use restrict/aliased, others are stored to a pointer in Function
4406 // memory and use RestrictPointer/AliasedPointer.
4407 if (originalParam(type.getQualifier().storage, type, false) ||
4408 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004409 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4410 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004411 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004412 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4413 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004414 }
4415 }
John Kessenichfad62972017-07-18 02:35:46 -06004416 };
4417
John Kessenich140f3df2015-06-26 16:58:36 -06004418 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4419 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004420 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004421 continue;
4422
4423 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004424 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004425 //
qining25262b32016-05-06 17:25:16 -04004426 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004427 // function. What it is an address of varies:
4428 //
John Kessenich4bf71552016-09-02 11:20:21 -06004429 // - "in" parameters not marked as "const" can be written to without modifying the calling
4430 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004431 //
4432 // - "const in" parameters can just be the r-value, as no writes need occur.
4433 //
John Kessenich4bf71552016-09-02 11:20:21 -06004434 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4435 // 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 -06004436
4437 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004438 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004439 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4440
John Kessenich155d3512019-08-08 23:29:20 -06004441#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004442 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4443 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004444#else
4445 bool implicitThis = false;
4446#endif
John Kessenich37789792017-03-21 23:56:40 -06004447
John Kessenichfad62972017-07-18 02:35:46 -06004448 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004449 for (int p = 0; p < (int)parameters.size(); ++p) {
4450 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4451 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004452 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004453 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004454 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004455 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4456 else
John Kessenich4bf71552016-09-02 11:20:21 -06004457 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004458 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004459 paramTypes.push_back(typeId);
4460 }
4461
4462 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004463 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4464 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004465 glslFunction->getName().c_str(), paramTypes,
4466 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004467 if (implicitThis)
4468 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004469
4470 // Track function to emit/call later
4471 functionMap[glslFunction->getName().c_str()] = function;
4472
4473 // Set the parameter id's
4474 for (int p = 0; p < (int)parameters.size(); ++p) {
4475 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4476 // give a name too
4477 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004478
4479 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004480 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004481 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004482 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004483 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004484 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004485 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004486 }
4487 }
4488}
4489
4490// Process all the initializers, while skipping the functions and link objects
4491void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4492{
4493 builder.setBuildPoint(shaderEntry->getLastBlock());
4494 for (int i = 0; i < (int)initializers.size(); ++i) {
4495 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004496 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4497 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004498
4499 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004500 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004501 initializer->traverse(this);
4502 }
4503 }
4504}
4505
4506// Process all the functions, while skipping initializers.
4507void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4508{
4509 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4510 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004511 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004512 node->traverse(this);
4513 }
4514}
4515
4516void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4517{
qining25262b32016-05-06 17:25:16 -04004518 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004519 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004520 currentFunction = functionMap[node->getName().c_str()];
4521 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004522 builder.setBuildPoint(functionBlock);
4523}
4524
John Kessenich8985fc92020-03-03 10:25:07 -07004525void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4526 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004527{
Rex Xufc618912015-09-09 16:42:49 +08004528 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004529
4530 glslang::TSampler sampler = {};
4531 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004532#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004533 bool f16ShadowCompare = false;
4534#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004535 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004536 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4537 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004538#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004539 f16ShadowCompare = sampler.shadow &&
4540 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004541#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004542 }
4543
John Kessenich140f3df2015-06-26 16:58:36 -06004544 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4545 builder.clearAccessChain();
4546 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004547
John Kessenicha28f7a72019-08-06 07:00:58 -06004548#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004549 // Special case l-value operands
4550 bool lvalue = false;
4551 switch (node.getOp()) {
4552 case glslang::EOpImageAtomicAdd:
4553 case glslang::EOpImageAtomicMin:
4554 case glslang::EOpImageAtomicMax:
4555 case glslang::EOpImageAtomicAnd:
4556 case glslang::EOpImageAtomicOr:
4557 case glslang::EOpImageAtomicXor:
4558 case glslang::EOpImageAtomicExchange:
4559 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004560 case glslang::EOpImageAtomicLoad:
4561 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004562 if (i == 0)
4563 lvalue = true;
4564 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004565 case glslang::EOpSparseImageLoad:
4566 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4567 lvalue = true;
4568 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004569 case glslang::EOpSparseTexture:
4570 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4571 lvalue = true;
4572 break;
4573 case glslang::EOpSparseTextureClamp:
4574 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4575 lvalue = true;
4576 break;
4577 case glslang::EOpSparseTextureLod:
4578 case glslang::EOpSparseTextureOffset:
4579 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4580 lvalue = true;
4581 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004582 case glslang::EOpSparseTextureFetch:
4583 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4584 lvalue = true;
4585 break;
4586 case glslang::EOpSparseTextureFetchOffset:
4587 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4588 lvalue = true;
4589 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004590 case glslang::EOpSparseTextureLodOffset:
4591 case glslang::EOpSparseTextureGrad:
4592 case glslang::EOpSparseTextureOffsetClamp:
4593 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4594 lvalue = true;
4595 break;
4596 case glslang::EOpSparseTextureGradOffset:
4597 case glslang::EOpSparseTextureGradClamp:
4598 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4599 lvalue = true;
4600 break;
4601 case glslang::EOpSparseTextureGradOffsetClamp:
4602 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4603 lvalue = true;
4604 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004605 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004606 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4607 lvalue = true;
4608 break;
4609 case glslang::EOpSparseTextureGatherOffset:
4610 case glslang::EOpSparseTextureGatherOffsets:
4611 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4612 lvalue = true;
4613 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004614 case glslang::EOpSparseTextureGatherLod:
4615 if (i == 3)
4616 lvalue = true;
4617 break;
4618 case glslang::EOpSparseTextureGatherLodOffset:
4619 case glslang::EOpSparseTextureGatherLodOffsets:
4620 if (i == 4)
4621 lvalue = true;
4622 break;
Rex Xu129799a2017-07-05 17:23:28 +08004623 case glslang::EOpSparseImageLoadLod:
4624 if (i == 3)
4625 lvalue = true;
4626 break;
Chao Chen3a137962018-09-19 11:41:27 -07004627 case glslang::EOpImageSampleFootprintNV:
4628 if (i == 4)
4629 lvalue = true;
4630 break;
4631 case glslang::EOpImageSampleFootprintClampNV:
4632 case glslang::EOpImageSampleFootprintLodNV:
4633 if (i == 5)
4634 lvalue = true;
4635 break;
4636 case glslang::EOpImageSampleFootprintGradNV:
4637 if (i == 6)
4638 lvalue = true;
4639 break;
4640 case glslang::EOpImageSampleFootprintGradClampNV:
4641 if (i == 7)
4642 lvalue = true;
4643 break;
Rex Xufc618912015-09-09 16:42:49 +08004644 default:
4645 break;
4646 }
4647
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004648 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004649 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004650 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4651 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4652 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004653#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004654 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004655 }
4656}
4657
John Kessenichfc51d282015-08-19 13:34:18 -06004658void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004659{
John Kessenichfc51d282015-08-19 13:34:18 -06004660 builder.clearAccessChain();
4661 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004662 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004663}
John Kessenich140f3df2015-06-26 16:58:36 -06004664
John Kessenichfc51d282015-08-19 13:34:18 -06004665spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4666{
John Kesseniche485c7a2017-05-31 18:50:53 -06004667 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004668 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004669
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004670 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004671
John Kessenichfc51d282015-08-19 13:34:18 -06004672 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004673
John Kessenichf43c7392019-03-31 10:51:57 -06004674 const glslang::TType &imageType = node->getAsAggregate()
4675 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4676 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004677 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004678#ifdef GLSLANG_WEB
4679 const bool f16ShadowCompare = false;
4680#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004681 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004682 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4683 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004684#endif
4685
John Kessenichf43c7392019-03-31 10:51:57 -06004686 const auto signExtensionMask = [&]() {
4687 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4688 if (sampler.type == glslang::EbtUint)
4689 return spv::ImageOperandsZeroExtendMask;
4690 else if (sampler.type == glslang::EbtInt)
4691 return spv::ImageOperandsSignExtendMask;
4692 }
4693 return spv::ImageOperandsMaskNone;
4694 };
4695
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004696 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4697
John Kessenichfc51d282015-08-19 13:34:18 -06004698 std::vector<spv::Id> arguments;
4699 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004700 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004701 else
4702 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004703 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004704
4705 spv::Builder::TextureParameters params = { };
4706 params.sampler = arguments[0];
4707
Rex Xu04db3f52015-09-16 11:44:02 +08004708 glslang::TCrackedTextureOp cracked;
4709 node->crackTexture(sampler, cracked);
4710
amhagan05506bb2017-06-13 16:53:02 -04004711 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004712
John Kessenichfc51d282015-08-19 13:34:18 -06004713 // Check for queries
4714 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004715 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4716 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004717 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004718
John Kessenichfc51d282015-08-19 13:34:18 -06004719 switch (node->getOp()) {
4720 case glslang::EOpImageQuerySize:
4721 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004722 if (arguments.size() > 1) {
4723 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004724 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004725 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004726 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004727#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004728 case glslang::EOpImageQuerySamples:
4729 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004730 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004731 case glslang::EOpTextureQueryLod:
4732 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004733 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004734 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004735 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004736 case glslang::EOpSparseTexelsResident:
4737 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004738#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004739 default:
4740 assert(0);
4741 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004742 }
John Kessenich140f3df2015-06-26 16:58:36 -06004743 }
4744
LoopDawg4425f242018-02-18 11:40:01 -07004745 int components = node->getType().getVectorSize();
4746
4747 if (node->getOp() == glslang::EOpTextureFetch) {
4748 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4749 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4750 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4751 // here around e.g. which ones return scalars or other types.
4752 components = 4;
4753 }
4754
4755 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4756
4757 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4758
Rex Xufc618912015-09-09 16:42:49 +08004759 // Check for image functions other than queries
4760 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004761 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004762 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004763 spv::IdImmediate image = { true, *(opIt++) };
4764 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004765
4766 // Handle subpass operations
4767 // TODO: GLSL should change to have the "MS" only on the type rather than the
4768 // built-in function.
4769 if (cracked.subpass) {
4770 // add on the (0,0) coordinate
4771 spv::Id zero = builder.makeIntConstant(0);
4772 std::vector<spv::Id> comps;
4773 comps.push_back(zero);
4774 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004775 spv::IdImmediate coord = { true,
4776 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4777 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004778 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4779 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004780 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004781 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4782 }
4783 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004784 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004785 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004786 spv::IdImmediate imageOperand = { true, *(opIt++) };
4787 operands.push_back(imageOperand);
4788 }
John Kessenich6c292d32016-02-15 20:58:50 -07004789 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004790 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4791 builder.setPrecision(result, precision);
4792 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004793 }
4794
John Kessenich149afc32018-08-14 13:31:43 -06004795 spv::IdImmediate coord = { true, *(opIt++) };
4796 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004797 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004798 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004799 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004800 mask = mask | spv::ImageOperandsSampleMask;
4801 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004802 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004803 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4804 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004805 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004806 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004807 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4808 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004809 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004810 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004811 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4812 operands.push_back(imageOperands);
4813 }
4814 if (mask & spv::ImageOperandsSampleMask) {
4815 spv::IdImmediate imageOperand = { true, *opIt++ };
4816 operands.push_back(imageOperand);
4817 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004818 if (mask & spv::ImageOperandsLodMask) {
4819 spv::IdImmediate imageOperand = { true, *opIt++ };
4820 operands.push_back(imageOperand);
4821 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004822 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004823 spv::IdImmediate imageOperand = { true,
4824 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004825 operands.push_back(imageOperand);
4826 }
4827
John Kessenich149afc32018-08-14 13:31:43 -06004828 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004829 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004830
John Kessenich149afc32018-08-14 13:31:43 -06004831 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004832 builder.setPrecision(result[0], precision);
4833
4834 // If needed, add a conversion constructor to the proper size.
4835 if (components != node->getType().getVectorSize())
4836 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4837
4838 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004839 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004840
Jeff Bolz36831c92018-09-05 10:11:41 -05004841 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004842 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004843 spv::IdImmediate texel = { true, *(opIt + 1) };
4844 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004845 } else {
4846 spv::IdImmediate texel = { true, *opIt };
4847 operands.push_back(texel);
4848 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004849
4850 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004851 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004852 mask = mask | spv::ImageOperandsSampleMask;
4853 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004854 if (cracked.lod) {
4855 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4856 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4857 mask = mask | spv::ImageOperandsLodMask;
4858 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004859 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4860 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004861 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004862 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004863 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4864 operands.push_back(imageOperands);
4865 }
4866 if (mask & spv::ImageOperandsSampleMask) {
4867 spv::IdImmediate imageOperand = { true, *opIt++ };
4868 operands.push_back(imageOperand);
4869 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004870 if (mask & spv::ImageOperandsLodMask) {
4871 spv::IdImmediate imageOperand = { true, *opIt++ };
4872 operands.push_back(imageOperand);
4873 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004874 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004875 spv::IdImmediate imageOperand = { true,
4876 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004877 operands.push_back(imageOperand);
4878 }
4879
John Kessenich56bab042015-09-16 10:54:31 -06004880 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004881 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004882 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004883 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004884 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4885 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004886 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004887 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004888 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4889
Jeff Bolz36831c92018-09-05 10:11:41 -05004890 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004891 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004892 mask = mask | spv::ImageOperandsSampleMask;
4893 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004894 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004895 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4896 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4897
Jeff Bolz36831c92018-09-05 10:11:41 -05004898 mask = mask | spv::ImageOperandsLodMask;
4899 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004900 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4901 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004902 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004903 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004904 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004905 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004906 }
4907 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004908 spv::IdImmediate imageOperand = { true, *opIt++ };
4909 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004910 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004911 if (mask & spv::ImageOperandsLodMask) {
4912 spv::IdImmediate imageOperand = { true, *opIt++ };
4913 operands.push_back(imageOperand);
4914 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004915 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004916 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4917 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004918 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004919 }
4920
4921 // Create the return type that was a special structure
4922 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004923 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004924 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4925 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4926
4927 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4928
4929 // Decode the return type
4930 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4931 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004932 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004933 // Process image atomic operations
4934
4935 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4936 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004937 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004938 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004939 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004940
Jeff Bolz36831c92018-09-05 10:11:41 -05004941 spv::Id resultTypeId;
4942 // imageAtomicStore has a void return type so base the pointer type on
4943 // the type of the value operand.
4944 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004945 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004946 } else {
4947 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4948 }
John Kessenich56bab042015-09-16 10:54:31 -06004949 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004950 if (imageType.getQualifier().nonUniform) {
4951 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4952 }
Rex Xufc618912015-09-09 16:42:49 +08004953
4954 std::vector<spv::Id> operands;
4955 operands.push_back(pointer);
4956 for (; opIt != arguments.end(); ++opIt)
4957 operands.push_back(*opIt);
4958
John Kessenich8985fc92020-03-03 10:25:07 -07004959 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4960 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004961 }
4962 }
4963
John Kessenicha28f7a72019-08-06 07:00:58 -06004964#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004965 // Check for fragment mask functions other than queries
4966 if (cracked.fragMask) {
4967 assert(sampler.ms);
4968
4969 auto opIt = arguments.begin();
4970 std::vector<spv::Id> operands;
4971
4972 // Extract the image if necessary
4973 if (builder.isSampledImage(params.sampler))
4974 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4975
4976 operands.push_back(params.sampler);
4977 ++opIt;
4978
4979 if (sampler.isSubpass()) {
4980 // add on the (0,0) coordinate
4981 spv::Id zero = builder.makeIntConstant(0);
4982 std::vector<spv::Id> comps;
4983 comps.push_back(zero);
4984 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004985 operands.push_back(builder.makeCompositeConstant(
4986 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04004987 }
4988
4989 for (; opIt != arguments.end(); ++opIt)
4990 operands.push_back(*opIt);
4991
4992 spv::Op fragMaskOp = spv::OpNop;
4993 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4994 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4995 else if (node->getOp() == glslang::EOpFragmentFetch)
4996 fragMaskOp = spv::OpFragmentFetchAMD;
4997
4998 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4999 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5000 return builder.createOp(fragMaskOp, resultType(), operands);
5001 }
5002#endif
5003
Rex Xufc618912015-09-09 16:42:49 +08005004 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005005 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005006 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005007 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005008
John Kessenichfc51d282015-08-19 13:34:18 -06005009 // check for bias argument
5010 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005011 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005012 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005013 if (cracked.gather)
5014 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005015
5016 if (f16ShadowCompare)
5017 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005018 if (cracked.offset)
5019 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005020 else if (cracked.offsets)
5021 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005022 if (cracked.grad)
5023 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005024 if (cracked.lodClamp)
5025 ++nonBiasArgCount;
5026 if (sparse)
5027 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005028 if (imageFootprint)
5029 //Following three extra arguments
5030 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5031 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005032 if ((int)arguments.size() > nonBiasArgCount)
5033 bias = true;
5034 }
5035
John Kessenicha5c33d62016-06-02 23:45:21 -06005036 // See if the sampler param should really be just the SPV image part
5037 if (cracked.fetch) {
5038 // a fetch needs to have the image extracted first
5039 if (builder.isSampledImage(params.sampler))
5040 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5041 }
5042
John Kessenicha28f7a72019-08-06 07:00:58 -06005043#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005044 if (cracked.gather) {
5045 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5046 if (bias || cracked.lod ||
5047 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5048 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005049 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005050 }
5051 }
5052#endif
5053
John Kessenichfc51d282015-08-19 13:34:18 -06005054 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005055
John Kessenichfc51d282015-08-19 13:34:18 -06005056 params.coords = arguments[1];
5057 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005058 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005059
5060 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005061 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005062 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005063 ++extraArgs;
5064 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005065 params.Dref = arguments[2];
5066 ++extraArgs;
5067 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005068 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005069 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005070 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005071 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005072 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005073 dRefComp = builder.getNumComponents(params.coords) - 1;
5074 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005075 params.Dref = builder.createCompositeExtract(params.coords,
5076 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005077 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005078
5079 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005080 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005081 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005082 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005083 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5084 !(glslangIntermediate->getStage() == EShLangCompute &&
5085 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005086 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5087 noImplicitLod = true;
5088 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005089
5090 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005091 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005092 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005093 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005094 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005095
5096 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005097 if (cracked.grad) {
5098 params.gradX = arguments[2 + extraArgs];
5099 params.gradY = arguments[3 + extraArgs];
5100 extraArgs += 2;
5101 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005102
5103 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005104 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005105 params.offset = arguments[2 + extraArgs];
5106 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005107 } else if (cracked.offsets) {
5108 params.offsets = arguments[2 + extraArgs];
5109 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005110 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005111
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005112#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005113 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005114 if (cracked.lodClamp) {
5115 params.lodClamp = arguments[2 + extraArgs];
5116 ++extraArgs;
5117 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005118 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005119 if (sparse) {
5120 params.texelOut = arguments[2 + extraArgs];
5121 ++extraArgs;
5122 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005123 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005124 if (cracked.gather && ! sampler.shadow) {
5125 // default component is 0, if missing, otherwise an argument
5126 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005127 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005128 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005129 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005130 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005131 }
Chao Chen3a137962018-09-19 11:41:27 -07005132 spv::Id resultStruct = spv::NoResult;
5133 if (imageFootprint) {
5134 //Following three extra arguments
5135 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5136 params.granularity = arguments[2 + extraArgs];
5137 params.coarse = arguments[3 + extraArgs];
5138 resultStruct = arguments[4 + extraArgs];
5139 extraArgs += 3;
5140 }
5141#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005142 // bias
5143 if (bias) {
5144 params.bias = arguments[2 + extraArgs];
5145 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005146 }
John Kessenichfc51d282015-08-19 13:34:18 -06005147
John Kessenicha28f7a72019-08-06 07:00:58 -06005148#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005149 if (imageFootprint) {
5150 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5151 builder.addCapability(spv::CapabilityImageFootprintNV);
5152
5153
5154 //resultStructType(OpenGL type) contains 5 elements:
5155 //struct gl_TextureFootprint2DNV {
5156 // uvec2 anchor;
5157 // uvec2 offset;
5158 // uvec2 mask;
5159 // uint lod;
5160 // uint granularity;
5161 //};
5162 //or
5163 //struct gl_TextureFootprint3DNV {
5164 // uvec3 anchor;
5165 // uvec3 offset;
5166 // uvec2 mask;
5167 // uint lod;
5168 // uint granularity;
5169 //};
5170 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5171 assert(builder.isStructType(resultStructType));
5172
5173 //resType (SPIR-V type) contains 6 elements:
5174 //Member 0 must be a Boolean type scalar(LOD),
5175 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5176 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5177 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5178 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5179 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5180 std::vector<spv::Id> members;
5181 members.push_back(resultType());
5182 for (int i = 0; i < 5; i++) {
5183 members.push_back(builder.getContainedTypeId(resultStructType, i));
5184 }
5185 spv::Id resType = builder.makeStructType(members, "ResType");
5186
5187 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005188 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5189 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005190
5191 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5192 for (int i = 0; i < 5; i++) {
5193 builder.clearAccessChain();
5194 builder.setAccessChainLValue(resultStruct);
5195
5196 //Accessing to a struct we created, no coherent flag is set
5197 spv::Builder::AccessChain::CoherentFlags flags;
5198 flags.clear();
5199
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005200 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005201 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5202 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005203 }
5204 return builder.createCompositeExtract(res, resultType(), 0);
5205 }
5206#endif
5207
John Kessenich65336482016-06-16 14:06:26 -06005208 // projective component (might not to move)
5209 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5210 // are divided by the last component of P."
5211 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5212 // unused components will appear after all used components."
5213 if (cracked.proj) {
5214 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5215 int projTargetComp;
5216 switch (sampler.dim) {
5217 case glslang::Esd1D: projTargetComp = 1; break;
5218 case glslang::Esd2D: projTargetComp = 2; break;
5219 case glslang::EsdRect: projTargetComp = 2; break;
5220 default: projTargetComp = projSourceComp; break;
5221 }
5222 // copy the projective coordinate if we have to
5223 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005224 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005225 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005226 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005227 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005228 }
5229 }
5230
John Kessenichf8d1d742019-10-21 06:55:11 -06005231#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005232 // nonprivate
5233 if (imageType.getQualifier().nonprivate) {
5234 params.nonprivate = true;
5235 }
5236
5237 // volatile
5238 if (imageType.getQualifier().volatil) {
5239 params.volatil = true;
5240 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005241#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005242
St0fFa1184dd2018-04-09 21:08:14 +02005243 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005244 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5245 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005246 );
LoopDawg4425f242018-02-18 11:40:01 -07005247
5248 if (components != node->getType().getVectorSize())
5249 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5250
5251 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005252}
5253
5254spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5255{
5256 // Grab the function's pointer from the previously created function
5257 spv::Function* function = functionMap[node->getName().c_str()];
5258 if (! function)
5259 return 0;
5260
5261 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5262 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5263
5264 // See comments in makeFunctions() for details about the semantics for parameter passing.
5265 //
5266 // These imply we need a four step process:
5267 // 1. Evaluate the arguments
5268 // 2. Allocate and make copies of in, out, and inout arguments
5269 // 3. Make the call
5270 // 4. Copy back the results
5271
John Kessenichd3ed90b2018-05-04 11:43:03 -06005272 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005273 std::vector<spv::Builder::AccessChain> lValues;
5274 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005275 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005276 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005277 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005278 // build l-value
5279 builder.clearAccessChain();
5280 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005281 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005282 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005283 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005284 // save l-value
5285 lValues.push_back(builder.getAccessChain());
5286 } else {
5287 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005288 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005289 }
5290 }
5291
5292 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5293 // copy the original into that space.
5294 //
5295 // Also, build up the list of actual arguments to pass in for the call
5296 int lValueCount = 0;
5297 int rValueCount = 0;
5298 std::vector<spv::Id> spvArgs;
5299 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5300 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005301 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005302 builder.setAccessChain(lValues[lValueCount]);
5303 arg = builder.accessChainGetLValue();
5304 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005305 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005306 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005307 arg = builder.createVariable(spv::StorageClassFunction,
5308 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005309 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5310 // need to copy the input into output space
5311 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005312 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005313 builder.clearAccessChain();
5314 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005315 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005316 }
5317 ++lValueCount;
5318 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005319 // process r-value, which involves a copy for a type mismatch
5320 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5321 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5322 builder.clearAccessChain();
5323 builder.setAccessChainLValue(argCopy);
5324 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5325 arg = builder.createLoad(argCopy);
5326 } else
5327 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005328 ++rValueCount;
5329 }
5330 spvArgs.push_back(arg);
5331 }
5332
5333 // 3. Make the call.
5334 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005335 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005336
5337 // 4. Copy back out an "out" arguments.
5338 lValueCount = 0;
5339 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005340 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005341 ++lValueCount;
5342 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005343 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5344 spv::Id copy = builder.createLoad(spvArgs[a]);
5345 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005346 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005347 }
5348 ++lValueCount;
5349 }
5350 }
5351
5352 return result;
5353}
5354
5355// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005356spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005357 spv::Id typeId, spv::Id left, spv::Id right,
5358 glslang::TBasicType typeProxy, bool reduceComparison)
5359{
John Kessenich66011cb2018-03-06 16:12:04 -07005360 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5361 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005362 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005363
5364 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005365 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005366 bool comparison = false;
5367
5368 switch (op) {
5369 case glslang::EOpAdd:
5370 case glslang::EOpAddAssign:
5371 if (isFloat)
5372 binOp = spv::OpFAdd;
5373 else
5374 binOp = spv::OpIAdd;
5375 break;
5376 case glslang::EOpSub:
5377 case glslang::EOpSubAssign:
5378 if (isFloat)
5379 binOp = spv::OpFSub;
5380 else
5381 binOp = spv::OpISub;
5382 break;
5383 case glslang::EOpMul:
5384 case glslang::EOpMulAssign:
5385 if (isFloat)
5386 binOp = spv::OpFMul;
5387 else
5388 binOp = spv::OpIMul;
5389 break;
5390 case glslang::EOpVectorTimesScalar:
5391 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005392 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005393 if (builder.isVector(right))
5394 std::swap(left, right);
5395 assert(builder.isScalar(right));
5396 needMatchingVectors = false;
5397 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005398 } else if (isFloat)
5399 binOp = spv::OpFMul;
5400 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005401 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005402 break;
5403 case glslang::EOpVectorTimesMatrix:
5404 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005405 binOp = spv::OpVectorTimesMatrix;
5406 break;
5407 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005408 binOp = spv::OpMatrixTimesVector;
5409 break;
5410 case glslang::EOpMatrixTimesScalar:
5411 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005412 binOp = spv::OpMatrixTimesScalar;
5413 break;
5414 case glslang::EOpMatrixTimesMatrix:
5415 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005416 binOp = spv::OpMatrixTimesMatrix;
5417 break;
5418 case glslang::EOpOuterProduct:
5419 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005420 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005421 break;
5422
5423 case glslang::EOpDiv:
5424 case glslang::EOpDivAssign:
5425 if (isFloat)
5426 binOp = spv::OpFDiv;
5427 else if (isUnsigned)
5428 binOp = spv::OpUDiv;
5429 else
5430 binOp = spv::OpSDiv;
5431 break;
5432 case glslang::EOpMod:
5433 case glslang::EOpModAssign:
5434 if (isFloat)
5435 binOp = spv::OpFMod;
5436 else if (isUnsigned)
5437 binOp = spv::OpUMod;
5438 else
5439 binOp = spv::OpSMod;
5440 break;
5441 case glslang::EOpRightShift:
5442 case glslang::EOpRightShiftAssign:
5443 if (isUnsigned)
5444 binOp = spv::OpShiftRightLogical;
5445 else
5446 binOp = spv::OpShiftRightArithmetic;
5447 break;
5448 case glslang::EOpLeftShift:
5449 case glslang::EOpLeftShiftAssign:
5450 binOp = spv::OpShiftLeftLogical;
5451 break;
5452 case glslang::EOpAnd:
5453 case glslang::EOpAndAssign:
5454 binOp = spv::OpBitwiseAnd;
5455 break;
5456 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005457 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005458 binOp = spv::OpLogicalAnd;
5459 break;
5460 case glslang::EOpInclusiveOr:
5461 case glslang::EOpInclusiveOrAssign:
5462 binOp = spv::OpBitwiseOr;
5463 break;
5464 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005465 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005466 binOp = spv::OpLogicalOr;
5467 break;
5468 case glslang::EOpExclusiveOr:
5469 case glslang::EOpExclusiveOrAssign:
5470 binOp = spv::OpBitwiseXor;
5471 break;
5472 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005473 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005474 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005475 break;
5476
Ian Romanickb3bd4022019-01-21 08:57:25 -08005477 case glslang::EOpAbsDifference:
5478 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5479 break;
5480
5481 case glslang::EOpAddSaturate:
5482 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5483 break;
5484
5485 case glslang::EOpSubSaturate:
5486 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5487 break;
5488
5489 case glslang::EOpAverage:
5490 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5491 break;
5492
5493 case glslang::EOpAverageRounded:
5494 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5495 break;
5496
5497 case glslang::EOpMul32x16:
5498 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5499 break;
5500
John Kessenich140f3df2015-06-26 16:58:36 -06005501 case glslang::EOpLessThan:
5502 case glslang::EOpGreaterThan:
5503 case glslang::EOpLessThanEqual:
5504 case glslang::EOpGreaterThanEqual:
5505 case glslang::EOpEqual:
5506 case glslang::EOpNotEqual:
5507 case glslang::EOpVectorEqual:
5508 case glslang::EOpVectorNotEqual:
5509 comparison = true;
5510 break;
5511 default:
5512 break;
5513 }
5514
John Kessenich7c1aa102015-10-15 13:29:11 -06005515 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005516 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005517 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005518 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5519 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005520 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005521
5522 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005523 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005524 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005525
qining25262b32016-05-06 17:25:16 -04005526 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005527 decorations.addNoContraction(builder, result);
5528 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005529 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005530 }
5531
5532 if (! comparison)
5533 return 0;
5534
John Kessenich7c1aa102015-10-15 13:29:11 -06005535 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005536
John Kessenich4583b612016-08-07 19:14:22 -06005537 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005538 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5539 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005540 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005541 return result;
5542 }
John Kessenich140f3df2015-06-26 16:58:36 -06005543
5544 switch (op) {
5545 case glslang::EOpLessThan:
5546 if (isFloat)
5547 binOp = spv::OpFOrdLessThan;
5548 else if (isUnsigned)
5549 binOp = spv::OpULessThan;
5550 else
5551 binOp = spv::OpSLessThan;
5552 break;
5553 case glslang::EOpGreaterThan:
5554 if (isFloat)
5555 binOp = spv::OpFOrdGreaterThan;
5556 else if (isUnsigned)
5557 binOp = spv::OpUGreaterThan;
5558 else
5559 binOp = spv::OpSGreaterThan;
5560 break;
5561 case glslang::EOpLessThanEqual:
5562 if (isFloat)
5563 binOp = spv::OpFOrdLessThanEqual;
5564 else if (isUnsigned)
5565 binOp = spv::OpULessThanEqual;
5566 else
5567 binOp = spv::OpSLessThanEqual;
5568 break;
5569 case glslang::EOpGreaterThanEqual:
5570 if (isFloat)
5571 binOp = spv::OpFOrdGreaterThanEqual;
5572 else if (isUnsigned)
5573 binOp = spv::OpUGreaterThanEqual;
5574 else
5575 binOp = spv::OpSGreaterThanEqual;
5576 break;
5577 case glslang::EOpEqual:
5578 case glslang::EOpVectorEqual:
5579 if (isFloat)
5580 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005581 else if (isBool)
5582 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005583 else
5584 binOp = spv::OpIEqual;
5585 break;
5586 case glslang::EOpNotEqual:
5587 case glslang::EOpVectorNotEqual:
5588 if (isFloat)
5589 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005590 else if (isBool)
5591 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005592 else
5593 binOp = spv::OpINotEqual;
5594 break;
5595 default:
5596 break;
5597 }
5598
qining25262b32016-05-06 17:25:16 -04005599 if (binOp != spv::OpNop) {
5600 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005601 decorations.addNoContraction(builder, result);
5602 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005603 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005604 }
John Kessenich140f3df2015-06-26 16:58:36 -06005605
5606 return 0;
5607}
5608
John Kessenich04bb8a02015-12-12 12:28:14 -07005609//
5610// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5611// These can be any of:
5612//
5613// matrix * scalar
5614// scalar * matrix
5615// matrix * matrix linear algebraic
5616// matrix * vector
5617// vector * matrix
5618// matrix * matrix componentwise
5619// matrix op matrix op in {+, -, /}
5620// matrix op scalar op in {+, -, /}
5621// scalar op matrix op in {+, -, /}
5622//
John Kessenichead86222018-03-28 18:01:20 -06005623spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5624 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005625{
5626 bool firstClass = true;
5627
5628 // First, handle first-class matrix operations (* and matrix/scalar)
5629 switch (op) {
5630 case spv::OpFDiv:
5631 if (builder.isMatrix(left) && builder.isScalar(right)) {
5632 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005633 spv::Id resultType = builder.getTypeId(right);
5634 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005635 op = spv::OpMatrixTimesScalar;
5636 } else
5637 firstClass = false;
5638 break;
5639 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005640 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005641 std::swap(left, right);
5642 assert(builder.isScalar(right));
5643 break;
5644 case spv::OpVectorTimesMatrix:
5645 assert(builder.isVector(left));
5646 assert(builder.isMatrix(right));
5647 break;
5648 case spv::OpMatrixTimesVector:
5649 assert(builder.isMatrix(left));
5650 assert(builder.isVector(right));
5651 break;
5652 case spv::OpMatrixTimesMatrix:
5653 assert(builder.isMatrix(left));
5654 assert(builder.isMatrix(right));
5655 break;
5656 default:
5657 firstClass = false;
5658 break;
5659 }
5660
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005661 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5662 firstClass = true;
5663
qining25262b32016-05-06 17:25:16 -04005664 if (firstClass) {
5665 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005666 decorations.addNoContraction(builder, result);
5667 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005668 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005669 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005670
LoopDawg592860c2016-06-09 08:57:35 -06005671 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005672 // The result type of all of them is the same type as the (a) matrix operand.
5673 // The algorithm is to:
5674 // - break the matrix(es) into vectors
5675 // - smear any scalar to a vector
5676 // - do vector operations
5677 // - make a matrix out the vector results
5678 switch (op) {
5679 case spv::OpFAdd:
5680 case spv::OpFSub:
5681 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005682 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005683 case spv::OpFMul:
5684 {
5685 // one time set up...
5686 bool leftMat = builder.isMatrix(left);
5687 bool rightMat = builder.isMatrix(right);
5688 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5689 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5690 spv::Id scalarType = builder.getScalarTypeId(typeId);
5691 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5692 std::vector<spv::Id> results;
5693 spv::Id smearVec = spv::NoResult;
5694 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005695 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005696 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005697 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005698
5699 // do each vector op
5700 for (unsigned int c = 0; c < numCols; ++c) {
5701 std::vector<unsigned int> indexes;
5702 indexes.push_back(c);
5703 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5704 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005705 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005706 decorations.addNoContraction(builder, result);
5707 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005708 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005709 }
5710
5711 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005712 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005713 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005714 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005715 }
5716 default:
5717 assert(0);
5718 return spv::NoResult;
5719 }
5720}
5721
John Kessenichead86222018-03-28 18:01:20 -06005722spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005723 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005724{
5725 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005726 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005727 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005728 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5729 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005730
5731 switch (op) {
5732 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005733 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005734 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005735 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005736 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005737 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005738 unaryOp = spv::OpSNegate;
5739 break;
5740
5741 case glslang::EOpLogicalNot:
5742 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005743 unaryOp = spv::OpLogicalNot;
5744 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005745 case glslang::EOpBitwiseNot:
5746 unaryOp = spv::OpNot;
5747 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005748
John Kessenich140f3df2015-06-26 16:58:36 -06005749 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005750 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005751 break;
5752 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005753 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005754 break;
5755 case glslang::EOpTranspose:
5756 unaryOp = spv::OpTranspose;
5757 break;
5758
5759 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005760 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005761 break;
5762 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005763 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005764 break;
5765 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005766 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005767 break;
5768 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005769 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005770 break;
5771 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005772 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005773 break;
5774 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005775 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005776 break;
5777 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005778 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005779 break;
5780 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005781 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005782 break;
5783
5784 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005785 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005786 break;
5787 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005788 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005789 break;
5790 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005791 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005792 break;
5793 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005794 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005795 break;
5796 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005797 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005798 break;
5799 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005800 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005801 break;
5802
5803 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005804 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005805 break;
5806 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005807 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005808 break;
5809
5810 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005811 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005812 break;
5813 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005814 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005815 break;
5816 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005817 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005818 break;
5819 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005820 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005821 break;
5822 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005823 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005824 break;
5825 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005826 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005827 break;
5828
5829 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005830 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005831 break;
5832 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005833 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005834 break;
5835 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005836 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005837 break;
5838 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005839 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005840 break;
5841 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005842 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005843 break;
5844 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005845 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005846 break;
5847
5848 case glslang::EOpIsNan:
5849 unaryOp = spv::OpIsNan;
5850 break;
5851 case glslang::EOpIsInf:
5852 unaryOp = spv::OpIsInf;
5853 break;
LoopDawg592860c2016-06-09 08:57:35 -06005854 case glslang::EOpIsFinite:
5855 unaryOp = spv::OpIsFinite;
5856 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005857
Rex Xucbc426e2015-12-15 16:03:10 +08005858 case glslang::EOpFloatBitsToInt:
5859 case glslang::EOpFloatBitsToUint:
5860 case glslang::EOpIntBitsToFloat:
5861 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005862 case glslang::EOpDoubleBitsToInt64:
5863 case glslang::EOpDoubleBitsToUint64:
5864 case glslang::EOpInt64BitsToDouble:
5865 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005866 case glslang::EOpFloat16BitsToInt16:
5867 case glslang::EOpFloat16BitsToUint16:
5868 case glslang::EOpInt16BitsToFloat16:
5869 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005870 unaryOp = spv::OpBitcast;
5871 break;
5872
John Kessenich140f3df2015-06-26 16:58:36 -06005873 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005874 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005875 break;
5876 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005877 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005878 break;
5879 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005880 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005881 break;
5882 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005883 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005884 break;
5885 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005886 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005887 break;
5888 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005889 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005890 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005891#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005892 case glslang::EOpPackSnorm4x8:
5893 libCall = spv::GLSLstd450PackSnorm4x8;
5894 break;
5895 case glslang::EOpUnpackSnorm4x8:
5896 libCall = spv::GLSLstd450UnpackSnorm4x8;
5897 break;
5898 case glslang::EOpPackUnorm4x8:
5899 libCall = spv::GLSLstd450PackUnorm4x8;
5900 break;
5901 case glslang::EOpUnpackUnorm4x8:
5902 libCall = spv::GLSLstd450UnpackUnorm4x8;
5903 break;
5904 case glslang::EOpPackDouble2x32:
5905 libCall = spv::GLSLstd450PackDouble2x32;
5906 break;
5907 case glslang::EOpUnpackDouble2x32:
5908 libCall = spv::GLSLstd450UnpackDouble2x32;
5909 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005910#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005911
Rex Xu8ff43de2016-04-22 16:51:45 +08005912 case glslang::EOpPackInt2x32:
5913 case glslang::EOpUnpackInt2x32:
5914 case glslang::EOpPackUint2x32:
5915 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005916 case glslang::EOpPack16:
5917 case glslang::EOpPack32:
5918 case glslang::EOpPack64:
5919 case glslang::EOpUnpack32:
5920 case glslang::EOpUnpack16:
5921 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005922 case glslang::EOpPackInt2x16:
5923 case glslang::EOpUnpackInt2x16:
5924 case glslang::EOpPackUint2x16:
5925 case glslang::EOpUnpackUint2x16:
5926 case glslang::EOpPackInt4x16:
5927 case glslang::EOpUnpackInt4x16:
5928 case glslang::EOpPackUint4x16:
5929 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005930 case glslang::EOpPackFloat2x16:
5931 case glslang::EOpUnpackFloat2x16:
5932 unaryOp = spv::OpBitcast;
5933 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005934
John Kessenich140f3df2015-06-26 16:58:36 -06005935 case glslang::EOpDPdx:
5936 unaryOp = spv::OpDPdx;
5937 break;
5938 case glslang::EOpDPdy:
5939 unaryOp = spv::OpDPdy;
5940 break;
5941 case glslang::EOpFwidth:
5942 unaryOp = spv::OpFwidth;
5943 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005944
John Kessenich140f3df2015-06-26 16:58:36 -06005945 case glslang::EOpAny:
5946 unaryOp = spv::OpAny;
5947 break;
5948 case glslang::EOpAll:
5949 unaryOp = spv::OpAll;
5950 break;
5951
5952 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005953 if (isFloat)
5954 libCall = spv::GLSLstd450FAbs;
5955 else
5956 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005957 break;
5958 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005959 if (isFloat)
5960 libCall = spv::GLSLstd450FSign;
5961 else
5962 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005963 break;
5964
John Kessenicha28f7a72019-08-06 07:00:58 -06005965#ifndef GLSLANG_WEB
5966 case glslang::EOpDPdxFine:
5967 unaryOp = spv::OpDPdxFine;
5968 break;
5969 case glslang::EOpDPdyFine:
5970 unaryOp = spv::OpDPdyFine;
5971 break;
5972 case glslang::EOpFwidthFine:
5973 unaryOp = spv::OpFwidthFine;
5974 break;
5975 case glslang::EOpDPdxCoarse:
5976 unaryOp = spv::OpDPdxCoarse;
5977 break;
5978 case glslang::EOpDPdyCoarse:
5979 unaryOp = spv::OpDPdyCoarse;
5980 break;
5981 case glslang::EOpFwidthCoarse:
5982 unaryOp = spv::OpFwidthCoarse;
5983 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04005984 case glslang::EOpRayQueryProceed:
5985 unaryOp = spv::OpRayQueryProceedKHR;
5986 break;
5987 case glslang::EOpRayQueryGetRayTMin:
5988 unaryOp = spv::OpRayQueryGetRayTMinKHR;
5989 break;
5990 case glslang::EOpRayQueryGetRayFlags:
5991 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
5992 break;
5993 case glslang::EOpRayQueryGetWorldRayOrigin:
5994 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
5995 break;
5996 case glslang::EOpRayQueryGetWorldRayDirection:
5997 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
5998 break;
5999 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6000 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6001 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006002 case glslang::EOpInterpolateAtCentroid:
6003 if (typeProxy == glslang::EbtFloat16)
6004 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6005 libCall = spv::GLSLstd450InterpolateAtCentroid;
6006 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006007 case glslang::EOpAtomicCounterIncrement:
6008 case glslang::EOpAtomicCounterDecrement:
6009 case glslang::EOpAtomicCounter:
6010 {
6011 // Handle all of the atomics in one place, in createAtomicOperation()
6012 std::vector<spv::Id> operands;
6013 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006014 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006015 }
6016
John Kessenichfc51d282015-08-19 13:34:18 -06006017 case glslang::EOpBitFieldReverse:
6018 unaryOp = spv::OpBitReverse;
6019 break;
6020 case glslang::EOpBitCount:
6021 unaryOp = spv::OpBitCount;
6022 break;
6023 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006024 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006025 break;
6026 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006027 if (isUnsigned)
6028 libCall = spv::GLSLstd450FindUMsb;
6029 else
6030 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006031 break;
6032
Ian Romanickb3bd4022019-01-21 08:57:25 -08006033 case glslang::EOpCountLeadingZeros:
6034 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6035 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6036 unaryOp = spv::OpUCountLeadingZerosINTEL;
6037 break;
6038
6039 case glslang::EOpCountTrailingZeros:
6040 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6041 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6042 unaryOp = spv::OpUCountTrailingZerosINTEL;
6043 break;
6044
Rex Xu574ab042016-04-14 16:53:07 +08006045 case glslang::EOpBallot:
6046 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006047 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006048 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006049 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006050 case glslang::EOpMinInvocations:
6051 case glslang::EOpMaxInvocations:
6052 case glslang::EOpAddInvocations:
6053 case glslang::EOpMinInvocationsNonUniform:
6054 case glslang::EOpMaxInvocationsNonUniform:
6055 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006056 case glslang::EOpMinInvocationsInclusiveScan:
6057 case glslang::EOpMaxInvocationsInclusiveScan:
6058 case glslang::EOpAddInvocationsInclusiveScan:
6059 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6060 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6061 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6062 case glslang::EOpMinInvocationsExclusiveScan:
6063 case glslang::EOpMaxInvocationsExclusiveScan:
6064 case glslang::EOpAddInvocationsExclusiveScan:
6065 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6066 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6067 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006068 {
6069 std::vector<spv::Id> operands;
6070 operands.push_back(operand);
6071 return createInvocationsOperation(op, typeId, operands, typeProxy);
6072 }
John Kessenich66011cb2018-03-06 16:12:04 -07006073 case glslang::EOpSubgroupAll:
6074 case glslang::EOpSubgroupAny:
6075 case glslang::EOpSubgroupAllEqual:
6076 case glslang::EOpSubgroupBroadcastFirst:
6077 case glslang::EOpSubgroupBallot:
6078 case glslang::EOpSubgroupInverseBallot:
6079 case glslang::EOpSubgroupBallotBitCount:
6080 case glslang::EOpSubgroupBallotInclusiveBitCount:
6081 case glslang::EOpSubgroupBallotExclusiveBitCount:
6082 case glslang::EOpSubgroupBallotFindLSB:
6083 case glslang::EOpSubgroupBallotFindMSB:
6084 case glslang::EOpSubgroupAdd:
6085 case glslang::EOpSubgroupMul:
6086 case glslang::EOpSubgroupMin:
6087 case glslang::EOpSubgroupMax:
6088 case glslang::EOpSubgroupAnd:
6089 case glslang::EOpSubgroupOr:
6090 case glslang::EOpSubgroupXor:
6091 case glslang::EOpSubgroupInclusiveAdd:
6092 case glslang::EOpSubgroupInclusiveMul:
6093 case glslang::EOpSubgroupInclusiveMin:
6094 case glslang::EOpSubgroupInclusiveMax:
6095 case glslang::EOpSubgroupInclusiveAnd:
6096 case glslang::EOpSubgroupInclusiveOr:
6097 case glslang::EOpSubgroupInclusiveXor:
6098 case glslang::EOpSubgroupExclusiveAdd:
6099 case glslang::EOpSubgroupExclusiveMul:
6100 case glslang::EOpSubgroupExclusiveMin:
6101 case glslang::EOpSubgroupExclusiveMax:
6102 case glslang::EOpSubgroupExclusiveAnd:
6103 case glslang::EOpSubgroupExclusiveOr:
6104 case glslang::EOpSubgroupExclusiveXor:
6105 case glslang::EOpSubgroupQuadSwapHorizontal:
6106 case glslang::EOpSubgroupQuadSwapVertical:
6107 case glslang::EOpSubgroupQuadSwapDiagonal: {
6108 std::vector<spv::Id> operands;
6109 operands.push_back(operand);
6110 return createSubgroupOperation(op, typeId, operands, typeProxy);
6111 }
Rex Xu9d93a232016-05-05 12:30:44 +08006112 case glslang::EOpMbcnt:
6113 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6114 libCall = spv::MbcntAMD;
6115 break;
6116
6117 case glslang::EOpCubeFaceIndex:
6118 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6119 libCall = spv::CubeFaceIndexAMD;
6120 break;
6121
6122 case glslang::EOpCubeFaceCoord:
6123 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6124 libCall = spv::CubeFaceCoordAMD;
6125 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006126 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006127 unaryOp = spv::OpGroupNonUniformPartitionNV;
6128 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006129 case glslang::EOpConstructReference:
6130 unaryOp = spv::OpBitcast;
6131 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006132#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006133
6134 case glslang::EOpCopyObject:
6135 unaryOp = spv::OpCopyObject;
6136 break;
6137
John Kessenich140f3df2015-06-26 16:58:36 -06006138 default:
6139 return 0;
6140 }
6141
6142 spv::Id id;
6143 if (libCall >= 0) {
6144 std::vector<spv::Id> args;
6145 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006146 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006147 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006148 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006149 }
John Kessenich140f3df2015-06-26 16:58:36 -06006150
John Kessenichb9197c82019-08-11 07:41:45 -06006151 decorations.addNoContraction(builder, id);
6152 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006153 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006154}
6155
John Kessenich7a53f762016-01-20 11:19:27 -07006156// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006157spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6158 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006159{
6160 // Handle unary operations vector by vector.
6161 // The result type is the same type as the original type.
6162 // The algorithm is to:
6163 // - break the matrix into vectors
6164 // - apply the operation to each vector
6165 // - make a matrix out the vector results
6166
6167 // get the types sorted out
6168 int numCols = builder.getNumColumns(operand);
6169 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006170 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6171 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006172 std::vector<spv::Id> results;
6173
6174 // do each vector op
6175 for (int c = 0; c < numCols; ++c) {
6176 std::vector<unsigned int> indexes;
6177 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006178 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6179 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006180 decorations.addNoContraction(builder, destVec);
6181 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006182 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006183 }
6184
6185 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006186 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006187 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006188 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006189}
6190
John Kessenichad7645f2018-06-04 19:11:25 -06006191// For converting integers where both the bitwidth and the signedness could
6192// change, but only do the width change here. The caller is still responsible
6193// for the signedness conversion.
6194spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006195{
John Kessenichad7645f2018-06-04 19:11:25 -06006196 // Get the result type width, based on the type to convert to.
6197 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006198 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006199 case glslang::EOpConvInt16ToUint8:
6200 case glslang::EOpConvIntToUint8:
6201 case glslang::EOpConvInt64ToUint8:
6202 case glslang::EOpConvUint16ToInt8:
6203 case glslang::EOpConvUintToInt8:
6204 case glslang::EOpConvUint64ToInt8:
6205 width = 8;
6206 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006207 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006208 case glslang::EOpConvIntToUint16:
6209 case glslang::EOpConvInt64ToUint16:
6210 case glslang::EOpConvUint8ToInt16:
6211 case glslang::EOpConvUintToInt16:
6212 case glslang::EOpConvUint64ToInt16:
6213 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006214 break;
6215 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006216 case glslang::EOpConvInt16ToUint:
6217 case glslang::EOpConvInt64ToUint:
6218 case glslang::EOpConvUint8ToInt:
6219 case glslang::EOpConvUint16ToInt:
6220 case glslang::EOpConvUint64ToInt:
6221 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006222 break;
6223 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006224 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006225 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006226 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006227 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006228 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006229 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006230 break;
6231
6232 default:
6233 assert(false && "Default missing");
6234 break;
6235 }
6236
John Kessenichad7645f2018-06-04 19:11:25 -06006237 // Get the conversion operation and result type,
6238 // based on the target width, but the source type.
6239 spv::Id type = spv::NoType;
6240 spv::Op convOp = spv::OpNop;
6241 switch(op) {
6242 case glslang::EOpConvInt8ToUint16:
6243 case glslang::EOpConvInt8ToUint:
6244 case glslang::EOpConvInt8ToUint64:
6245 case glslang::EOpConvInt16ToUint8:
6246 case glslang::EOpConvInt16ToUint:
6247 case glslang::EOpConvInt16ToUint64:
6248 case glslang::EOpConvIntToUint8:
6249 case glslang::EOpConvIntToUint16:
6250 case glslang::EOpConvIntToUint64:
6251 case glslang::EOpConvInt64ToUint8:
6252 case glslang::EOpConvInt64ToUint16:
6253 case glslang::EOpConvInt64ToUint:
6254 convOp = spv::OpSConvert;
6255 type = builder.makeIntType(width);
6256 break;
6257 default:
6258 convOp = spv::OpUConvert;
6259 type = builder.makeUintType(width);
6260 break;
6261 }
6262
John Kessenich66011cb2018-03-06 16:12:04 -07006263 if (vectorSize > 0)
6264 type = builder.makeVectorType(type, vectorSize);
6265
John Kessenichad7645f2018-06-04 19:11:25 -06006266 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006267}
6268
John Kessenichead86222018-03-28 18:01:20 -06006269spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6270 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006271{
6272 spv::Op convOp = spv::OpNop;
6273 spv::Id zero = 0;
6274 spv::Id one = 0;
6275
6276 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6277
6278 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006279 case glslang::EOpConvIntToBool:
6280 case glslang::EOpConvUintToBool:
6281 zero = builder.makeUintConstant(0);
6282 zero = makeSmearedConstant(zero, vectorSize);
6283 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006284 case glslang::EOpConvFloatToBool:
6285 zero = builder.makeFloatConstant(0.0F);
6286 zero = makeSmearedConstant(zero, vectorSize);
6287 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006288 case glslang::EOpConvBoolToFloat:
6289 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006290 zero = builder.makeFloatConstant(0.0F);
6291 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006292 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006293
John Kessenich140f3df2015-06-26 16:58:36 -06006294 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006295 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006296#ifndef GLSLANG_WEB
6297 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006298 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006299 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006300 } else
6301#endif
6302 {
6303 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006304 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006305 }
Rex Xucabbb782017-03-24 13:41:14 +08006306
John Kessenich140f3df2015-06-26 16:58:36 -06006307 convOp = spv::OpSelect;
6308 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006309
John Kessenich140f3df2015-06-26 16:58:36 -06006310 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006311 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006312#ifndef GLSLANG_WEB
6313 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006314 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006315 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006316 } else
6317#endif
6318 {
6319 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006320 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006321 }
Rex Xucabbb782017-03-24 13:41:14 +08006322
John Kessenich140f3df2015-06-26 16:58:36 -06006323 convOp = spv::OpSelect;
6324 break;
6325
John Kessenich66011cb2018-03-06 16:12:04 -07006326 case glslang::EOpConvInt8ToFloat16:
6327 case glslang::EOpConvInt8ToFloat:
6328 case glslang::EOpConvInt8ToDouble:
6329 case glslang::EOpConvInt16ToFloat16:
6330 case glslang::EOpConvInt16ToFloat:
6331 case glslang::EOpConvInt16ToDouble:
6332 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006333 case glslang::EOpConvIntToFloat:
6334 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006335 case glslang::EOpConvInt64ToFloat:
6336 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006337 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006338 convOp = spv::OpConvertSToF;
6339 break;
6340
John Kessenich66011cb2018-03-06 16:12:04 -07006341 case glslang::EOpConvUint8ToFloat16:
6342 case glslang::EOpConvUint8ToFloat:
6343 case glslang::EOpConvUint8ToDouble:
6344 case glslang::EOpConvUint16ToFloat16:
6345 case glslang::EOpConvUint16ToFloat:
6346 case glslang::EOpConvUint16ToDouble:
6347 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006348 case glslang::EOpConvUintToFloat:
6349 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006350 case glslang::EOpConvUint64ToFloat:
6351 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006352 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006353 convOp = spv::OpConvertUToF;
6354 break;
6355
John Kessenich66011cb2018-03-06 16:12:04 -07006356 case glslang::EOpConvFloat16ToInt8:
6357 case glslang::EOpConvFloatToInt8:
6358 case glslang::EOpConvDoubleToInt8:
6359 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006360 case glslang::EOpConvFloatToInt16:
6361 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006362 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006363 case glslang::EOpConvFloatToInt:
6364 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006365 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006366 case glslang::EOpConvFloatToInt64:
6367 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006368 convOp = spv::OpConvertFToS;
6369 break;
6370
John Kessenich66011cb2018-03-06 16:12:04 -07006371 case glslang::EOpConvUint8ToInt8:
6372 case glslang::EOpConvInt8ToUint8:
6373 case glslang::EOpConvUint16ToInt16:
6374 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006375 case glslang::EOpConvUintToInt:
6376 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006377 case glslang::EOpConvUint64ToInt64:
6378 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006379 if (builder.isInSpecConstCodeGenMode()) {
6380 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006381#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006382 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6383 zero = builder.makeUint8Constant(0);
6384 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006385 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006386 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6387 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006388 } else
6389#endif
6390 {
Rex Xucabbb782017-03-24 13:41:14 +08006391 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006392 }
qining189b2032016-04-12 23:16:20 -04006393 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006394 // Use OpIAdd, instead of OpBitcast to do the conversion when
6395 // generating for OpSpecConstantOp instruction.
6396 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6397 }
6398 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006399 convOp = spv::OpBitcast;
6400 break;
6401
John Kessenich66011cb2018-03-06 16:12:04 -07006402 case glslang::EOpConvFloat16ToUint8:
6403 case glslang::EOpConvFloatToUint8:
6404 case glslang::EOpConvDoubleToUint8:
6405 case glslang::EOpConvFloat16ToUint16:
6406 case glslang::EOpConvFloatToUint16:
6407 case glslang::EOpConvDoubleToUint16:
6408 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006409 case glslang::EOpConvFloatToUint:
6410 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006411 case glslang::EOpConvFloatToUint64:
6412 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006413 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006414 convOp = spv::OpConvertFToU;
6415 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006416
John Kessenich39697cd2019-08-08 10:35:51 -06006417#ifndef GLSLANG_WEB
6418 case glslang::EOpConvInt8ToBool:
6419 case glslang::EOpConvUint8ToBool:
6420 zero = builder.makeUint8Constant(0);
6421 zero = makeSmearedConstant(zero, vectorSize);
6422 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6423 case glslang::EOpConvInt16ToBool:
6424 case glslang::EOpConvUint16ToBool:
6425 zero = builder.makeUint16Constant(0);
6426 zero = makeSmearedConstant(zero, vectorSize);
6427 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6428 case glslang::EOpConvInt64ToBool:
6429 case glslang::EOpConvUint64ToBool:
6430 zero = builder.makeUint64Constant(0);
6431 zero = makeSmearedConstant(zero, vectorSize);
6432 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6433 case glslang::EOpConvDoubleToBool:
6434 zero = builder.makeDoubleConstant(0.0);
6435 zero = makeSmearedConstant(zero, vectorSize);
6436 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6437 case glslang::EOpConvFloat16ToBool:
6438 zero = builder.makeFloat16Constant(0.0F);
6439 zero = makeSmearedConstant(zero, vectorSize);
6440 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6441 case glslang::EOpConvBoolToDouble:
6442 convOp = spv::OpSelect;
6443 zero = builder.makeDoubleConstant(0.0);
6444 one = builder.makeDoubleConstant(1.0);
6445 break;
6446 case glslang::EOpConvBoolToFloat16:
6447 convOp = spv::OpSelect;
6448 zero = builder.makeFloat16Constant(0.0F);
6449 one = builder.makeFloat16Constant(1.0F);
6450 break;
6451 case glslang::EOpConvBoolToInt8:
6452 zero = builder.makeInt8Constant(0);
6453 one = builder.makeInt8Constant(1);
6454 convOp = spv::OpSelect;
6455 break;
6456 case glslang::EOpConvBoolToUint8:
6457 zero = builder.makeUint8Constant(0);
6458 one = builder.makeUint8Constant(1);
6459 convOp = spv::OpSelect;
6460 break;
6461 case glslang::EOpConvBoolToInt16:
6462 zero = builder.makeInt16Constant(0);
6463 one = builder.makeInt16Constant(1);
6464 convOp = spv::OpSelect;
6465 break;
6466 case glslang::EOpConvBoolToUint16:
6467 zero = builder.makeUint16Constant(0);
6468 one = builder.makeUint16Constant(1);
6469 convOp = spv::OpSelect;
6470 break;
6471 case glslang::EOpConvDoubleToFloat:
6472 case glslang::EOpConvFloatToDouble:
6473 case glslang::EOpConvDoubleToFloat16:
6474 case glslang::EOpConvFloat16ToDouble:
6475 case glslang::EOpConvFloatToFloat16:
6476 case glslang::EOpConvFloat16ToFloat:
6477 convOp = spv::OpFConvert;
6478 if (builder.isMatrixType(destType))
6479 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6480 break;
6481
John Kessenich66011cb2018-03-06 16:12:04 -07006482 case glslang::EOpConvInt8ToInt16:
6483 case glslang::EOpConvInt8ToInt:
6484 case glslang::EOpConvInt8ToInt64:
6485 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006486 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006487 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006488 case glslang::EOpConvIntToInt8:
6489 case glslang::EOpConvIntToInt16:
6490 case glslang::EOpConvIntToInt64:
6491 case glslang::EOpConvInt64ToInt8:
6492 case glslang::EOpConvInt64ToInt16:
6493 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006494 convOp = spv::OpSConvert;
6495 break;
6496
John Kessenich66011cb2018-03-06 16:12:04 -07006497 case glslang::EOpConvUint8ToUint16:
6498 case glslang::EOpConvUint8ToUint:
6499 case glslang::EOpConvUint8ToUint64:
6500 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006501 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006502 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006503 case glslang::EOpConvUintToUint8:
6504 case glslang::EOpConvUintToUint16:
6505 case glslang::EOpConvUintToUint64:
6506 case glslang::EOpConvUint64ToUint8:
6507 case glslang::EOpConvUint64ToUint16:
6508 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006509 convOp = spv::OpUConvert;
6510 break;
6511
John Kessenich66011cb2018-03-06 16:12:04 -07006512 case glslang::EOpConvInt8ToUint16:
6513 case glslang::EOpConvInt8ToUint:
6514 case glslang::EOpConvInt8ToUint64:
6515 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006516 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006517 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006518 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006519 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006520 case glslang::EOpConvIntToUint64:
6521 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006522 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006523 case glslang::EOpConvInt64ToUint:
6524 case glslang::EOpConvUint8ToInt16:
6525 case glslang::EOpConvUint8ToInt:
6526 case glslang::EOpConvUint8ToInt64:
6527 case glslang::EOpConvUint16ToInt8:
6528 case glslang::EOpConvUint16ToInt:
6529 case glslang::EOpConvUint16ToInt64:
6530 case glslang::EOpConvUintToInt8:
6531 case glslang::EOpConvUintToInt16:
6532 case glslang::EOpConvUintToInt64:
6533 case glslang::EOpConvUint64ToInt8:
6534 case glslang::EOpConvUint64ToInt16:
6535 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006536 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006537 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006538
6539 if (builder.isInSpecConstCodeGenMode()) {
6540 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006541 switch(op) {
6542 case glslang::EOpConvInt16ToUint8:
6543 case glslang::EOpConvIntToUint8:
6544 case glslang::EOpConvInt64ToUint8:
6545 case glslang::EOpConvUint16ToInt8:
6546 case glslang::EOpConvUintToInt8:
6547 case glslang::EOpConvUint64ToInt8:
6548 zero = builder.makeUint8Constant(0);
6549 break;
6550 case glslang::EOpConvInt8ToUint16:
6551 case glslang::EOpConvIntToUint16:
6552 case glslang::EOpConvInt64ToUint16:
6553 case glslang::EOpConvUint8ToInt16:
6554 case glslang::EOpConvUintToInt16:
6555 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006556 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006557 break;
6558 case glslang::EOpConvInt8ToUint:
6559 case glslang::EOpConvInt16ToUint:
6560 case glslang::EOpConvInt64ToUint:
6561 case glslang::EOpConvUint8ToInt:
6562 case glslang::EOpConvUint16ToInt:
6563 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006564 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006565 break;
6566 case glslang::EOpConvInt8ToUint64:
6567 case glslang::EOpConvInt16ToUint64:
6568 case glslang::EOpConvIntToUint64:
6569 case glslang::EOpConvUint8ToInt64:
6570 case glslang::EOpConvUint16ToInt64:
6571 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006572 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006573 break;
6574 default:
6575 assert(false && "Default missing");
6576 break;
6577 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006578 zero = makeSmearedConstant(zero, vectorSize);
6579 // Use OpIAdd, instead of OpBitcast to do the conversion when
6580 // generating for OpSpecConstantOp instruction.
6581 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6582 }
6583 // For normal run-time conversion instruction, use OpBitcast.
6584 convOp = spv::OpBitcast;
6585 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006586 case glslang::EOpConvUint64ToPtr:
6587 convOp = spv::OpConvertUToPtr;
6588 break;
6589 case glslang::EOpConvPtrToUint64:
6590 convOp = spv::OpConvertPtrToU;
6591 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006592 case glslang::EOpConvPtrToUvec2:
6593 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006594 if (builder.isVector(operand))
6595 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6596 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006597 convOp = spv::OpBitcast;
6598 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006599#endif
6600
John Kessenich140f3df2015-06-26 16:58:36 -06006601 default:
6602 break;
6603 }
6604
6605 spv::Id result = 0;
6606 if (convOp == spv::OpNop)
6607 return result;
6608
6609 if (convOp == spv::OpSelect) {
6610 zero = makeSmearedConstant(zero, vectorSize);
6611 one = makeSmearedConstant(one, vectorSize);
6612 result = builder.createTriOp(convOp, destType, operand, one, zero);
6613 } else
6614 result = builder.createUnaryOp(convOp, destType, operand);
6615
John Kessenichead86222018-03-28 18:01:20 -06006616 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006617 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006618 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006619}
6620
6621spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6622{
6623 if (vectorSize == 0)
6624 return constant;
6625
6626 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6627 std::vector<spv::Id> components;
6628 for (int c = 0; c < vectorSize; ++c)
6629 components.push_back(constant);
6630 return builder.makeCompositeConstant(vectorTypeId, components);
6631}
6632
John Kessenich426394d2015-07-23 10:22:48 -06006633// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006634spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6635 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6636 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006637{
6638 spv::Op opCode = spv::OpNop;
6639
6640 switch (op) {
6641 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006642 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006643 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006644 opCode = spv::OpAtomicIAdd;
6645 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006646 case glslang::EOpAtomicCounterSubtract:
6647 opCode = spv::OpAtomicISub;
6648 break;
John Kessenich426394d2015-07-23 10:22:48 -06006649 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006650 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006651 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006652 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6653 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006654 break;
6655 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006656 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006657 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006658 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6659 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006660 break;
6661 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006662 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006663 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006664 opCode = spv::OpAtomicAnd;
6665 break;
6666 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006667 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006668 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006669 opCode = spv::OpAtomicOr;
6670 break;
6671 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006672 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006673 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006674 opCode = spv::OpAtomicXor;
6675 break;
6676 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006677 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006678 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006679 opCode = spv::OpAtomicExchange;
6680 break;
6681 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006682 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006683 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006684 opCode = spv::OpAtomicCompareExchange;
6685 break;
6686 case glslang::EOpAtomicCounterIncrement:
6687 opCode = spv::OpAtomicIIncrement;
6688 break;
6689 case glslang::EOpAtomicCounterDecrement:
6690 opCode = spv::OpAtomicIDecrement;
6691 break;
6692 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006693 case glslang::EOpImageAtomicLoad:
6694 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006695 opCode = spv::OpAtomicLoad;
6696 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006697 case glslang::EOpAtomicStore:
6698 case glslang::EOpImageAtomicStore:
6699 opCode = spv::OpAtomicStore;
6700 break;
John Kessenich426394d2015-07-23 10:22:48 -06006701 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006702 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006703 break;
6704 }
6705
Rex Xue8fe8b02017-09-26 15:42:56 +08006706 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6707 builder.addCapability(spv::CapabilityInt64Atomics);
6708
John Kessenich426394d2015-07-23 10:22:48 -06006709 // Sort out the operands
6710 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006711 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006712 // - compare-exchange swaps the value and comparator
6713 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006714 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006715 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6716 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6717 spv::Id scopeId;
6718 if (glslangIntermediate->usingVulkanMemoryModel()) {
6719 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6720 } else {
6721 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6722 }
6723 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006724 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6725 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006726 spv::MemorySemanticsVolatileMask :
6727 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006728 spv::Id semanticsId2 = semanticsId;
6729
6730 pointerId = operands[0];
6731 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6732 // no additional operands
6733 } else if (opCode == spv::OpAtomicCompareExchange) {
6734 compareId = operands[1];
6735 valueId = operands[2];
6736 if (operands.size() > 3) {
6737 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006738 semanticsId = builder.makeUintConstant(
6739 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6740 semanticsId2 = builder.makeUintConstant(
6741 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006742 }
6743 } else if (opCode == spv::OpAtomicLoad) {
6744 if (operands.size() > 1) {
6745 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006746 semanticsId = builder.makeUintConstant(
6747 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006748 }
6749 } else {
6750 // atomic store or RMW
6751 valueId = operands[1];
6752 if (operands.size() > 2) {
6753 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006754 semanticsId = builder.makeUintConstant
6755 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006756 }
Rex Xu04db3f52015-09-16 11:44:02 +08006757 }
John Kessenich426394d2015-07-23 10:22:48 -06006758
Jeff Bolz36831c92018-09-05 10:11:41 -05006759 // Check for capabilities
6760 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006761 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6762 spv::MemorySemanticsMakeVisibleKHRMask |
6763 spv::MemorySemanticsOutputMemoryKHRMask |
6764 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006765 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6766 }
John Kessenich426394d2015-07-23 10:22:48 -06006767
Jeff Bolz36831c92018-09-05 10:11:41 -05006768 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6769 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6770 }
John Kessenich48d6e792017-10-06 21:21:48 -06006771
Jeff Bolz36831c92018-09-05 10:11:41 -05006772 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6773 spvAtomicOperands.push_back(pointerId);
6774 spvAtomicOperands.push_back(scopeId);
6775 spvAtomicOperands.push_back(semanticsId);
6776 if (opCode == spv::OpAtomicCompareExchange) {
6777 spvAtomicOperands.push_back(semanticsId2);
6778 spvAtomicOperands.push_back(valueId);
6779 spvAtomicOperands.push_back(compareId);
6780 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6781 spvAtomicOperands.push_back(valueId);
6782 }
John Kessenich48d6e792017-10-06 21:21:48 -06006783
Jeff Bolz36831c92018-09-05 10:11:41 -05006784 if (opCode == spv::OpAtomicStore) {
6785 builder.createNoResultOp(opCode, spvAtomicOperands);
6786 return 0;
6787 } else {
6788 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6789
6790 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6791 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6792 if (op == glslang::EOpAtomicCounterDecrement)
6793 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6794
6795 return resultId;
6796 }
John Kessenich426394d2015-07-23 10:22:48 -06006797}
6798
John Kessenich91cef522016-05-05 16:45:40 -06006799// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006800spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6801 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006802{
John Kessenich66011cb2018-03-06 16:12:04 -07006803 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6804 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006805
Rex Xu51596642016-09-21 18:56:12 +08006806 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006807 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006808 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6809
chaocf200da82016-12-20 12:44:35 -08006810 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6811 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006812 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6813 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006814 } else if (op == glslang::EOpAnyInvocation ||
6815 op == glslang::EOpAllInvocations ||
6816 op == glslang::EOpAllInvocationsEqual) {
6817 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6818 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006819 } else {
6820 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006821 if (op == glslang::EOpMinInvocationsNonUniform ||
6822 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006823 op == glslang::EOpAddInvocationsNonUniform ||
6824 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6825 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6826 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6827 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6828 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6829 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006830 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006831
Rex Xu430ef402016-10-14 17:22:23 +08006832 switch (op) {
6833 case glslang::EOpMinInvocations:
6834 case glslang::EOpMaxInvocations:
6835 case glslang::EOpAddInvocations:
6836 case glslang::EOpMinInvocationsNonUniform:
6837 case glslang::EOpMaxInvocationsNonUniform:
6838 case glslang::EOpAddInvocationsNonUniform:
6839 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006840 break;
6841 case glslang::EOpMinInvocationsInclusiveScan:
6842 case glslang::EOpMaxInvocationsInclusiveScan:
6843 case glslang::EOpAddInvocationsInclusiveScan:
6844 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6845 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6846 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6847 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006848 break;
6849 case glslang::EOpMinInvocationsExclusiveScan:
6850 case glslang::EOpMaxInvocationsExclusiveScan:
6851 case glslang::EOpAddInvocationsExclusiveScan:
6852 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6853 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6854 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6855 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006856 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006857 default:
6858 break;
Rex Xu430ef402016-10-14 17:22:23 +08006859 }
John Kessenich149afc32018-08-14 13:31:43 -06006860 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6861 spvGroupOperands.push_back(scope);
6862 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006863 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006864 spvGroupOperands.push_back(groupOp);
6865 }
Rex Xu51596642016-09-21 18:56:12 +08006866 }
6867
John Kessenich149afc32018-08-14 13:31:43 -06006868 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6869 spv::IdImmediate op = { true, *opIt };
6870 spvGroupOperands.push_back(op);
6871 }
John Kessenich91cef522016-05-05 16:45:40 -06006872
6873 switch (op) {
6874 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006875 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006876 break;
John Kessenich91cef522016-05-05 16:45:40 -06006877 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006878 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006879 break;
John Kessenich91cef522016-05-05 16:45:40 -06006880 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006881 opCode = spv::OpSubgroupAllEqualKHR;
6882 break;
Rex Xu51596642016-09-21 18:56:12 +08006883 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006884 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006885 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006886 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006887 break;
6888 case glslang::EOpReadFirstInvocation:
6889 opCode = spv::OpSubgroupFirstInvocationKHR;
6890 break;
6891 case glslang::EOpBallot:
6892 {
6893 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6894 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6895 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6896 //
6897 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6898 //
6899 spv::Id uintType = builder.makeUintType(32);
6900 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6901 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6902
6903 std::vector<spv::Id> components;
6904 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6905 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6906
6907 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6908 return builder.createUnaryOp(spv::OpBitcast, typeId,
6909 builder.createCompositeConstruct(uvec2Type, components));
6910 }
6911
Rex Xu9d93a232016-05-05 12:30:44 +08006912 case glslang::EOpMinInvocations:
6913 case glslang::EOpMaxInvocations:
6914 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006915 case glslang::EOpMinInvocationsInclusiveScan:
6916 case glslang::EOpMaxInvocationsInclusiveScan:
6917 case glslang::EOpAddInvocationsInclusiveScan:
6918 case glslang::EOpMinInvocationsExclusiveScan:
6919 case glslang::EOpMaxInvocationsExclusiveScan:
6920 case glslang::EOpAddInvocationsExclusiveScan:
6921 if (op == glslang::EOpMinInvocations ||
6922 op == glslang::EOpMinInvocationsInclusiveScan ||
6923 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006924 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006925 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006926 else {
6927 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006928 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006929 else
Rex Xu51596642016-09-21 18:56:12 +08006930 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006931 }
Rex Xu430ef402016-10-14 17:22:23 +08006932 } else if (op == glslang::EOpMaxInvocations ||
6933 op == glslang::EOpMaxInvocationsInclusiveScan ||
6934 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006935 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006936 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006937 else {
6938 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006939 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006940 else
Rex Xu51596642016-09-21 18:56:12 +08006941 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006942 }
6943 } else {
6944 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006945 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006946 else
Rex Xu51596642016-09-21 18:56:12 +08006947 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006948 }
6949
Rex Xu2bbbe062016-08-23 15:41:05 +08006950 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006951 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006952
6953 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006954 case glslang::EOpMinInvocationsNonUniform:
6955 case glslang::EOpMaxInvocationsNonUniform:
6956 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006957 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6958 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6959 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6960 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6961 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6962 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6963 if (op == glslang::EOpMinInvocationsNonUniform ||
6964 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6965 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006966 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006967 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006968 else {
6969 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006970 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006971 else
Rex Xu51596642016-09-21 18:56:12 +08006972 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006973 }
6974 }
Rex Xu430ef402016-10-14 17:22:23 +08006975 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6976 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6977 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006978 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006979 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006980 else {
6981 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006982 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006983 else
Rex Xu51596642016-09-21 18:56:12 +08006984 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006985 }
6986 }
6987 else {
6988 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006989 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006990 else
Rex Xu51596642016-09-21 18:56:12 +08006991 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006992 }
6993
Rex Xu2bbbe062016-08-23 15:41:05 +08006994 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006995 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006996
6997 break;
John Kessenich91cef522016-05-05 16:45:40 -06006998 default:
6999 logger->missingFunctionality("invocation operation");
7000 return spv::NoResult;
7001 }
Rex Xu51596642016-09-21 18:56:12 +08007002
7003 assert(opCode != spv::OpNop);
7004 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007005}
7006
Rex Xu2bbbe062016-08-23 15:41:05 +08007007// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007008spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7009 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007010{
7011 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7012 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007013 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007014 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007015 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7016 op == spv::OpGroupSMinNonUniformAMD ||
7017 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7018 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007019 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7020
7021 // Handle group invocation operations scalar by scalar.
7022 // The result type is the same type as the original type.
7023 // The algorithm is to:
7024 // - break the vector into scalars
7025 // - apply the operation to each scalar
7026 // - make a vector out the scalar results
7027
7028 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007029 int numComponents = builder.getNumComponents(operands[0]);
7030 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007031 std::vector<spv::Id> results;
7032
7033 // do each scalar op
7034 for (int comp = 0; comp < numComponents; ++comp) {
7035 std::vector<unsigned int> indexes;
7036 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007037 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7038 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007039 if (op == spv::OpSubgroupReadInvocationKHR) {
7040 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007041 spv::IdImmediate operand = { true, operands[1] };
7042 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007043 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007044 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7045 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007046 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007047 spv::IdImmediate operand = { true, operands[1] };
7048 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007049 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007050 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7051 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007052 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007053 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007054 spvGroupOperands.push_back(scalar);
7055 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007056
Rex Xub7072052016-09-26 15:53:40 +08007057 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007058 }
7059
7060 // put the pieces together
7061 return builder.createCompositeConstruct(typeId, results);
7062}
Rex Xu2bbbe062016-08-23 15:41:05 +08007063
John Kessenich66011cb2018-03-06 16:12:04 -07007064// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007065spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7066 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007067{
7068 // Add the required capabilities.
7069 switch (op) {
7070 case glslang::EOpSubgroupElect:
7071 builder.addCapability(spv::CapabilityGroupNonUniform);
7072 break;
7073 case glslang::EOpSubgroupAll:
7074 case glslang::EOpSubgroupAny:
7075 case glslang::EOpSubgroupAllEqual:
7076 builder.addCapability(spv::CapabilityGroupNonUniform);
7077 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7078 break;
7079 case glslang::EOpSubgroupBroadcast:
7080 case glslang::EOpSubgroupBroadcastFirst:
7081 case glslang::EOpSubgroupBallot:
7082 case glslang::EOpSubgroupInverseBallot:
7083 case glslang::EOpSubgroupBallotBitExtract:
7084 case glslang::EOpSubgroupBallotBitCount:
7085 case glslang::EOpSubgroupBallotInclusiveBitCount:
7086 case glslang::EOpSubgroupBallotExclusiveBitCount:
7087 case glslang::EOpSubgroupBallotFindLSB:
7088 case glslang::EOpSubgroupBallotFindMSB:
7089 builder.addCapability(spv::CapabilityGroupNonUniform);
7090 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7091 break;
7092 case glslang::EOpSubgroupShuffle:
7093 case glslang::EOpSubgroupShuffleXor:
7094 builder.addCapability(spv::CapabilityGroupNonUniform);
7095 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7096 break;
7097 case glslang::EOpSubgroupShuffleUp:
7098 case glslang::EOpSubgroupShuffleDown:
7099 builder.addCapability(spv::CapabilityGroupNonUniform);
7100 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7101 break;
7102 case glslang::EOpSubgroupAdd:
7103 case glslang::EOpSubgroupMul:
7104 case glslang::EOpSubgroupMin:
7105 case glslang::EOpSubgroupMax:
7106 case glslang::EOpSubgroupAnd:
7107 case glslang::EOpSubgroupOr:
7108 case glslang::EOpSubgroupXor:
7109 case glslang::EOpSubgroupInclusiveAdd:
7110 case glslang::EOpSubgroupInclusiveMul:
7111 case glslang::EOpSubgroupInclusiveMin:
7112 case glslang::EOpSubgroupInclusiveMax:
7113 case glslang::EOpSubgroupInclusiveAnd:
7114 case glslang::EOpSubgroupInclusiveOr:
7115 case glslang::EOpSubgroupInclusiveXor:
7116 case glslang::EOpSubgroupExclusiveAdd:
7117 case glslang::EOpSubgroupExclusiveMul:
7118 case glslang::EOpSubgroupExclusiveMin:
7119 case glslang::EOpSubgroupExclusiveMax:
7120 case glslang::EOpSubgroupExclusiveAnd:
7121 case glslang::EOpSubgroupExclusiveOr:
7122 case glslang::EOpSubgroupExclusiveXor:
7123 builder.addCapability(spv::CapabilityGroupNonUniform);
7124 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7125 break;
7126 case glslang::EOpSubgroupClusteredAdd:
7127 case glslang::EOpSubgroupClusteredMul:
7128 case glslang::EOpSubgroupClusteredMin:
7129 case glslang::EOpSubgroupClusteredMax:
7130 case glslang::EOpSubgroupClusteredAnd:
7131 case glslang::EOpSubgroupClusteredOr:
7132 case glslang::EOpSubgroupClusteredXor:
7133 builder.addCapability(spv::CapabilityGroupNonUniform);
7134 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7135 break;
7136 case glslang::EOpSubgroupQuadBroadcast:
7137 case glslang::EOpSubgroupQuadSwapHorizontal:
7138 case glslang::EOpSubgroupQuadSwapVertical:
7139 case glslang::EOpSubgroupQuadSwapDiagonal:
7140 builder.addCapability(spv::CapabilityGroupNonUniform);
7141 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7142 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007143 case glslang::EOpSubgroupPartitionedAdd:
7144 case glslang::EOpSubgroupPartitionedMul:
7145 case glslang::EOpSubgroupPartitionedMin:
7146 case glslang::EOpSubgroupPartitionedMax:
7147 case glslang::EOpSubgroupPartitionedAnd:
7148 case glslang::EOpSubgroupPartitionedOr:
7149 case glslang::EOpSubgroupPartitionedXor:
7150 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7151 case glslang::EOpSubgroupPartitionedInclusiveMul:
7152 case glslang::EOpSubgroupPartitionedInclusiveMin:
7153 case glslang::EOpSubgroupPartitionedInclusiveMax:
7154 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7155 case glslang::EOpSubgroupPartitionedInclusiveOr:
7156 case glslang::EOpSubgroupPartitionedInclusiveXor:
7157 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7158 case glslang::EOpSubgroupPartitionedExclusiveMul:
7159 case glslang::EOpSubgroupPartitionedExclusiveMin:
7160 case glslang::EOpSubgroupPartitionedExclusiveMax:
7161 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7162 case glslang::EOpSubgroupPartitionedExclusiveOr:
7163 case glslang::EOpSubgroupPartitionedExclusiveXor:
7164 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7165 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7166 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007167 default: assert(0 && "Unhandled subgroup operation!");
7168 }
7169
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007170
7171 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7172 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007173 const bool isBool = typeProxy == glslang::EbtBool;
7174
7175 spv::Op opCode = spv::OpNop;
7176
7177 // Figure out which opcode to use.
7178 switch (op) {
7179 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7180 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7181 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7182 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7183 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7184 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7185 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7186 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7187 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7188 case glslang::EOpSubgroupBallotBitCount:
7189 case glslang::EOpSubgroupBallotInclusiveBitCount:
7190 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7191 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7192 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7193 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7194 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7195 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7196 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7197 case glslang::EOpSubgroupAdd:
7198 case glslang::EOpSubgroupInclusiveAdd:
7199 case glslang::EOpSubgroupExclusiveAdd:
7200 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007201 case glslang::EOpSubgroupPartitionedAdd:
7202 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7203 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007204 if (isFloat) {
7205 opCode = spv::OpGroupNonUniformFAdd;
7206 } else {
7207 opCode = spv::OpGroupNonUniformIAdd;
7208 }
7209 break;
7210 case glslang::EOpSubgroupMul:
7211 case glslang::EOpSubgroupInclusiveMul:
7212 case glslang::EOpSubgroupExclusiveMul:
7213 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007214 case glslang::EOpSubgroupPartitionedMul:
7215 case glslang::EOpSubgroupPartitionedInclusiveMul:
7216 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007217 if (isFloat) {
7218 opCode = spv::OpGroupNonUniformFMul;
7219 } else {
7220 opCode = spv::OpGroupNonUniformIMul;
7221 }
7222 break;
7223 case glslang::EOpSubgroupMin:
7224 case glslang::EOpSubgroupInclusiveMin:
7225 case glslang::EOpSubgroupExclusiveMin:
7226 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007227 case glslang::EOpSubgroupPartitionedMin:
7228 case glslang::EOpSubgroupPartitionedInclusiveMin:
7229 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007230 if (isFloat) {
7231 opCode = spv::OpGroupNonUniformFMin;
7232 } else if (isUnsigned) {
7233 opCode = spv::OpGroupNonUniformUMin;
7234 } else {
7235 opCode = spv::OpGroupNonUniformSMin;
7236 }
7237 break;
7238 case glslang::EOpSubgroupMax:
7239 case glslang::EOpSubgroupInclusiveMax:
7240 case glslang::EOpSubgroupExclusiveMax:
7241 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007242 case glslang::EOpSubgroupPartitionedMax:
7243 case glslang::EOpSubgroupPartitionedInclusiveMax:
7244 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007245 if (isFloat) {
7246 opCode = spv::OpGroupNonUniformFMax;
7247 } else if (isUnsigned) {
7248 opCode = spv::OpGroupNonUniformUMax;
7249 } else {
7250 opCode = spv::OpGroupNonUniformSMax;
7251 }
7252 break;
7253 case glslang::EOpSubgroupAnd:
7254 case glslang::EOpSubgroupInclusiveAnd:
7255 case glslang::EOpSubgroupExclusiveAnd:
7256 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007257 case glslang::EOpSubgroupPartitionedAnd:
7258 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7259 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007260 if (isBool) {
7261 opCode = spv::OpGroupNonUniformLogicalAnd;
7262 } else {
7263 opCode = spv::OpGroupNonUniformBitwiseAnd;
7264 }
7265 break;
7266 case glslang::EOpSubgroupOr:
7267 case glslang::EOpSubgroupInclusiveOr:
7268 case glslang::EOpSubgroupExclusiveOr:
7269 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007270 case glslang::EOpSubgroupPartitionedOr:
7271 case glslang::EOpSubgroupPartitionedInclusiveOr:
7272 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007273 if (isBool) {
7274 opCode = spv::OpGroupNonUniformLogicalOr;
7275 } else {
7276 opCode = spv::OpGroupNonUniformBitwiseOr;
7277 }
7278 break;
7279 case glslang::EOpSubgroupXor:
7280 case glslang::EOpSubgroupInclusiveXor:
7281 case glslang::EOpSubgroupExclusiveXor:
7282 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007283 case glslang::EOpSubgroupPartitionedXor:
7284 case glslang::EOpSubgroupPartitionedInclusiveXor:
7285 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007286 if (isBool) {
7287 opCode = spv::OpGroupNonUniformLogicalXor;
7288 } else {
7289 opCode = spv::OpGroupNonUniformBitwiseXor;
7290 }
7291 break;
7292 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7293 case glslang::EOpSubgroupQuadSwapHorizontal:
7294 case glslang::EOpSubgroupQuadSwapVertical:
7295 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7296 default: assert(0 && "Unhandled subgroup operation!");
7297 }
7298
John Kessenich149afc32018-08-14 13:31:43 -06007299 // get the right Group Operation
7300 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007301 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007302 default:
7303 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007304 case glslang::EOpSubgroupBallotBitCount:
7305 case glslang::EOpSubgroupAdd:
7306 case glslang::EOpSubgroupMul:
7307 case glslang::EOpSubgroupMin:
7308 case glslang::EOpSubgroupMax:
7309 case glslang::EOpSubgroupAnd:
7310 case glslang::EOpSubgroupOr:
7311 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007312 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007313 break;
7314 case glslang::EOpSubgroupBallotInclusiveBitCount:
7315 case glslang::EOpSubgroupInclusiveAdd:
7316 case glslang::EOpSubgroupInclusiveMul:
7317 case glslang::EOpSubgroupInclusiveMin:
7318 case glslang::EOpSubgroupInclusiveMax:
7319 case glslang::EOpSubgroupInclusiveAnd:
7320 case glslang::EOpSubgroupInclusiveOr:
7321 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007322 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007323 break;
7324 case glslang::EOpSubgroupBallotExclusiveBitCount:
7325 case glslang::EOpSubgroupExclusiveAdd:
7326 case glslang::EOpSubgroupExclusiveMul:
7327 case glslang::EOpSubgroupExclusiveMin:
7328 case glslang::EOpSubgroupExclusiveMax:
7329 case glslang::EOpSubgroupExclusiveAnd:
7330 case glslang::EOpSubgroupExclusiveOr:
7331 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007332 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007333 break;
7334 case glslang::EOpSubgroupClusteredAdd:
7335 case glslang::EOpSubgroupClusteredMul:
7336 case glslang::EOpSubgroupClusteredMin:
7337 case glslang::EOpSubgroupClusteredMax:
7338 case glslang::EOpSubgroupClusteredAnd:
7339 case glslang::EOpSubgroupClusteredOr:
7340 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007341 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007342 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007343 case glslang::EOpSubgroupPartitionedAdd:
7344 case glslang::EOpSubgroupPartitionedMul:
7345 case glslang::EOpSubgroupPartitionedMin:
7346 case glslang::EOpSubgroupPartitionedMax:
7347 case glslang::EOpSubgroupPartitionedAnd:
7348 case glslang::EOpSubgroupPartitionedOr:
7349 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007350 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007351 break;
7352 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7353 case glslang::EOpSubgroupPartitionedInclusiveMul:
7354 case glslang::EOpSubgroupPartitionedInclusiveMin:
7355 case glslang::EOpSubgroupPartitionedInclusiveMax:
7356 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7357 case glslang::EOpSubgroupPartitionedInclusiveOr:
7358 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007359 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007360 break;
7361 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7362 case glslang::EOpSubgroupPartitionedExclusiveMul:
7363 case glslang::EOpSubgroupPartitionedExclusiveMin:
7364 case glslang::EOpSubgroupPartitionedExclusiveMax:
7365 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7366 case glslang::EOpSubgroupPartitionedExclusiveOr:
7367 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007368 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007369 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007370 }
7371
John Kessenich149afc32018-08-14 13:31:43 -06007372 // build the instruction
7373 std::vector<spv::IdImmediate> spvGroupOperands;
7374
7375 // Every operation begins with the Execution Scope operand.
7376 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7377 spvGroupOperands.push_back(executionScope);
7378
7379 // Next, for all operations that use a Group Operation, push that as an operand.
7380 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007381 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007382 spvGroupOperands.push_back(groupOperand);
7383 }
7384
John Kessenich66011cb2018-03-06 16:12:04 -07007385 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007386 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7387 spv::IdImmediate operand = { true, *opIt };
7388 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007389 }
7390
7391 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007392 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007393 switch (op) {
7394 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007395 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7396 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7397 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7398 }
7399 if (directionId != spv::NoResult) {
7400 spv::IdImmediate direction = { true, directionId };
7401 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007402 }
7403
7404 return builder.createOp(opCode, typeId, spvGroupOperands);
7405}
7406
John Kessenich8985fc92020-03-03 10:25:07 -07007407spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7408 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007409{
John Kessenich66011cb2018-03-06 16:12:04 -07007410 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7411 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007412
John Kessenich140f3df2015-06-26 16:58:36 -06007413 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007414 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007415 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007416 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007417 spv::Id typeId0 = 0;
7418 if (consumedOperands > 0)
7419 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007420 spv::Id typeId1 = 0;
7421 if (consumedOperands > 1)
7422 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007423 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007424
7425 switch (op) {
7426 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007427 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007428 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007429 else if (isUnsigned)
7430 libCall = spv::GLSLstd450UMin;
7431 else
7432 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007433 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007434 break;
7435 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007436 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007437 break;
7438 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007439 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007440 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007441 else if (isUnsigned)
7442 libCall = spv::GLSLstd450UMax;
7443 else
7444 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007445 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007446 break;
7447 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007448 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007449 break;
7450 case glslang::EOpDot:
7451 opCode = spv::OpDot;
7452 break;
7453 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007454 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007455 break;
7456
7457 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007458 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007459 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007460 else if (isUnsigned)
7461 libCall = spv::GLSLstd450UClamp;
7462 else
7463 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007464 builder.promoteScalar(precision, operands.front(), operands[1]);
7465 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007466 break;
7467 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007468 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7469 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007470 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007471 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007472 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007473 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007474 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007475 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007476 break;
7477 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007478 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007479 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007480 break;
7481 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007482 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007483 builder.promoteScalar(precision, operands[0], operands[2]);
7484 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007485 break;
7486
7487 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007488 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007489 break;
7490 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007491 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007492 break;
7493 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007494 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007495 break;
7496 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007497 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007498 break;
7499 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007500 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007501 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007502 case glslang::EOpBarrier:
7503 {
7504 // This is for the extended controlBarrier function, with four operands.
7505 // The unextended barrier() goes through createNoArgOperation.
7506 assert(operands.size() == 4);
7507 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7508 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7509 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007510 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7511 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007512 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7513 spv::MemorySemanticsMakeVisibleKHRMask |
7514 spv::MemorySemanticsOutputMemoryKHRMask |
7515 spv::MemorySemanticsVolatileMask)) {
7516 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7517 }
John Kessenich8985fc92020-03-03 10:25:07 -07007518 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7519 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007520 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7521 }
7522 return 0;
7523 }
7524 break;
7525 case glslang::EOpMemoryBarrier:
7526 {
7527 // This is for the extended memoryBarrier function, with three operands.
7528 // The unextended memoryBarrier() goes through createNoArgOperation.
7529 assert(operands.size() == 3);
7530 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7531 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7532 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7533 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7534 spv::MemorySemanticsMakeVisibleKHRMask |
7535 spv::MemorySemanticsOutputMemoryKHRMask |
7536 spv::MemorySemanticsVolatileMask)) {
7537 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7538 }
7539 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7540 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7541 }
7542 return 0;
7543 }
7544 break;
7545
John Kessenicha28f7a72019-08-06 07:00:58 -06007546#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007547 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007548 if (typeProxy == glslang::EbtFloat16)
7549 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007550 libCall = spv::GLSLstd450InterpolateAtSample;
7551 break;
7552 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007553 if (typeProxy == glslang::EbtFloat16)
7554 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007555 libCall = spv::GLSLstd450InterpolateAtOffset;
7556 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007557 case glslang::EOpAddCarry:
7558 opCode = spv::OpIAddCarry;
7559 typeId = builder.makeStructResultType(typeId0, typeId0);
7560 consumedOperands = 2;
7561 break;
7562 case glslang::EOpSubBorrow:
7563 opCode = spv::OpISubBorrow;
7564 typeId = builder.makeStructResultType(typeId0, typeId0);
7565 consumedOperands = 2;
7566 break;
7567 case glslang::EOpUMulExtended:
7568 opCode = spv::OpUMulExtended;
7569 typeId = builder.makeStructResultType(typeId0, typeId0);
7570 consumedOperands = 2;
7571 break;
7572 case glslang::EOpIMulExtended:
7573 opCode = spv::OpSMulExtended;
7574 typeId = builder.makeStructResultType(typeId0, typeId0);
7575 consumedOperands = 2;
7576 break;
7577 case glslang::EOpBitfieldExtract:
7578 if (isUnsigned)
7579 opCode = spv::OpBitFieldUExtract;
7580 else
7581 opCode = spv::OpBitFieldSExtract;
7582 break;
7583 case glslang::EOpBitfieldInsert:
7584 opCode = spv::OpBitFieldInsert;
7585 break;
7586
7587 case glslang::EOpFma:
7588 libCall = spv::GLSLstd450Fma;
7589 break;
7590 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007591 {
7592 libCall = spv::GLSLstd450FrexpStruct;
7593 assert(builder.isPointerType(typeId1));
7594 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007595 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007596 if (width == 16)
7597 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7598 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007599 if (builder.getNumComponents(operands[0]) == 1)
7600 frexpIntType = builder.makeIntegerType(width, true);
7601 else
John Kessenich8985fc92020-03-03 10:25:07 -07007602 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7603 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007604 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7605 consumedOperands = 1;
7606 }
John Kessenich55e7d112015-11-15 21:33:39 -07007607 break;
7608 case glslang::EOpLdexp:
7609 libCall = spv::GLSLstd450Ldexp;
7610 break;
7611
Rex Xu574ab042016-04-14 16:53:07 +08007612 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007613 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007614
John Kessenich66011cb2018-03-06 16:12:04 -07007615 case glslang::EOpSubgroupBroadcast:
7616 case glslang::EOpSubgroupBallotBitExtract:
7617 case glslang::EOpSubgroupShuffle:
7618 case glslang::EOpSubgroupShuffleXor:
7619 case glslang::EOpSubgroupShuffleUp:
7620 case glslang::EOpSubgroupShuffleDown:
7621 case glslang::EOpSubgroupClusteredAdd:
7622 case glslang::EOpSubgroupClusteredMul:
7623 case glslang::EOpSubgroupClusteredMin:
7624 case glslang::EOpSubgroupClusteredMax:
7625 case glslang::EOpSubgroupClusteredAnd:
7626 case glslang::EOpSubgroupClusteredOr:
7627 case glslang::EOpSubgroupClusteredXor:
7628 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007629 case glslang::EOpSubgroupPartitionedAdd:
7630 case glslang::EOpSubgroupPartitionedMul:
7631 case glslang::EOpSubgroupPartitionedMin:
7632 case glslang::EOpSubgroupPartitionedMax:
7633 case glslang::EOpSubgroupPartitionedAnd:
7634 case glslang::EOpSubgroupPartitionedOr:
7635 case glslang::EOpSubgroupPartitionedXor:
7636 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7637 case glslang::EOpSubgroupPartitionedInclusiveMul:
7638 case glslang::EOpSubgroupPartitionedInclusiveMin:
7639 case glslang::EOpSubgroupPartitionedInclusiveMax:
7640 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7641 case glslang::EOpSubgroupPartitionedInclusiveOr:
7642 case glslang::EOpSubgroupPartitionedInclusiveXor:
7643 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7644 case glslang::EOpSubgroupPartitionedExclusiveMul:
7645 case glslang::EOpSubgroupPartitionedExclusiveMin:
7646 case glslang::EOpSubgroupPartitionedExclusiveMax:
7647 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7648 case glslang::EOpSubgroupPartitionedExclusiveOr:
7649 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007650 return createSubgroupOperation(op, typeId, operands, typeProxy);
7651
Rex Xu9d93a232016-05-05 12:30:44 +08007652 case glslang::EOpSwizzleInvocations:
7653 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7654 libCall = spv::SwizzleInvocationsAMD;
7655 break;
7656 case glslang::EOpSwizzleInvocationsMasked:
7657 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7658 libCall = spv::SwizzleInvocationsMaskedAMD;
7659 break;
7660 case glslang::EOpWriteInvocation:
7661 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7662 libCall = spv::WriteInvocationAMD;
7663 break;
7664
7665 case glslang::EOpMin3:
7666 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7667 if (isFloat)
7668 libCall = spv::FMin3AMD;
7669 else {
7670 if (isUnsigned)
7671 libCall = spv::UMin3AMD;
7672 else
7673 libCall = spv::SMin3AMD;
7674 }
7675 break;
7676 case glslang::EOpMax3:
7677 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7678 if (isFloat)
7679 libCall = spv::FMax3AMD;
7680 else {
7681 if (isUnsigned)
7682 libCall = spv::UMax3AMD;
7683 else
7684 libCall = spv::SMax3AMD;
7685 }
7686 break;
7687 case glslang::EOpMid3:
7688 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7689 if (isFloat)
7690 libCall = spv::FMid3AMD;
7691 else {
7692 if (isUnsigned)
7693 libCall = spv::UMid3AMD;
7694 else
7695 libCall = spv::SMid3AMD;
7696 }
7697 break;
7698
7699 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007700 if (typeProxy == glslang::EbtFloat16)
7701 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007702 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7703 libCall = spv::InterpolateAtVertexAMD;
7704 break;
Chao Chen3c366992018-09-19 11:41:59 -07007705
Daniel Kochdb32b242020-03-17 20:42:47 -04007706 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007707 {
7708 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007709 opCode = spv::OpReportIntersectionKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07007710 }
7711 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007712 case glslang::EOpTrace:
Chao Chenb50c02e2018-09-19 11:42:24 -07007713 {
Daniel Kochdb32b242020-03-17 20:42:47 -04007714 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007715 return 0;
7716 }
7717 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007718 case glslang::EOpExecuteCallable:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007719 {
Daniel Kochdb32b242020-03-17 20:42:47 -04007720 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007721 return 0;
7722 }
7723 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04007724 case glslang::EOpRayQueryInitialize: {
7725 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7726 return 0;
7727 } break;
7728 case glslang::EOpRayQueryTerminate: {
7729 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7730 return 0;
7731 } break;
7732 case glslang::EOpRayQueryGenerateIntersection: {
7733 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7734 return 0;
7735 } break;
7736 case glslang::EOpRayQueryConfirmIntersection: {
7737 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7738 return 0;
7739 } break;
7740 case glslang::EOpRayQueryProceed: {
7741 typeId = builder.makeBoolType();
7742 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007743 } break;
Torosdagli06c2eee2020-03-19 11:09:57 -04007744 case glslang::EOpRayQueryGetIntersectionType: {
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007745 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007746 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
7747 } break;
7748 case glslang::EOpRayQueryGetRayTMin: {
7749 typeId = builder.makeFloatType(32);
7750 opCode = spv::OpRayQueryGetRayTMinKHR;
7751 } break;
7752 case glslang::EOpRayQueryGetRayFlags: {
7753 typeId = builder.makeIntType(32);
7754 opCode = spv::OpRayQueryGetRayFlagsKHR;
7755 } break;
7756 case glslang::EOpRayQueryGetIntersectionT: {
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007757 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007758 opCode = spv::OpRayQueryGetIntersectionTKHR;
7759 } break;
7760 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex: {
7761 typeId = builder.makeIntType(32);
7762 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
7763 } break;
7764 case glslang::EOpRayQueryGetIntersectionInstanceId: {
7765 typeId = builder.makeIntType(32);
7766 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
7767 } break;
7768 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset: {
7769 typeId = builder.makeIntType(32);
7770 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
7771 } break;
7772 case glslang::EOpRayQueryGetIntersectionGeometryIndex: {
7773 typeId = builder.makeIntType(32);
7774 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
7775 } break;
7776 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex: {
7777 typeId = builder.makeIntType(32);
7778 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
7779 } break;
7780 case glslang::EOpRayQueryGetIntersectionBarycentrics: {
7781 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7782 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
7783 } break;
7784 case glslang::EOpRayQueryGetIntersectionFrontFace: {
7785 typeId = builder.makeBoolType();
7786 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
7787 } break;
7788 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque: {
7789 typeId = builder.makeBoolType();
7790 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
7791 } break;
7792 case glslang::EOpRayQueryGetIntersectionObjectRayDirection: {
7793 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7794 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
7795 } break;
7796 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin: {
7797 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7798 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
7799 } break;
7800 case glslang::EOpRayQueryGetWorldRayDirection: {
7801 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7802 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
7803 } break;
7804 case glslang::EOpRayQueryGetWorldRayOrigin: {
7805 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7806 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
7807 } break;
7808 case glslang::EOpRayQueryGetIntersectionObjectToWorld: {
7809 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007810 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
7811 } break;
7812 case glslang::EOpRayQueryGetIntersectionWorldToObject: {
7813 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007814 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
7815 } break;
Chao Chen3c366992018-09-19 11:41:59 -07007816 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7817 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7818 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007819 case glslang::EOpCooperativeMatrixMulAdd:
7820 opCode = spv::OpCooperativeMatrixMulAddNV;
7821 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007822#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007823 default:
7824 return 0;
7825 }
7826
7827 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007828 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007829 // Use an extended instruction from the standard library.
7830 // Construct the call arguments, without modifying the original operands vector.
7831 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7832 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007833 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007834 } else if (opCode == spv::OpDot && !isFloat) {
7835 // int dot(int, int)
7836 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7837 const int componentCount = builder.getNumComponents(operands[0]);
7838 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7839 builder.setPrecision(mulOp, precision);
7840 id = builder.createCompositeExtract(mulOp, typeId, 0);
7841 for (int i = 1; i < componentCount; ++i) {
7842 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007843 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007844 }
John Kessenich2359bd02015-12-06 19:29:11 -07007845 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007846 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007847 case 0:
7848 // should all be handled by visitAggregate and createNoArgOperation
7849 assert(0);
7850 return 0;
7851 case 1:
7852 // should all be handled by createUnaryOperation
7853 assert(0);
7854 return 0;
7855 case 2:
7856 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7857 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007858 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007859 // anything 3 or over doesn't have l-value operands, so all should be consumed
7860 assert(consumedOperands == operands.size());
7861 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007862 break;
7863 }
7864 }
7865
John Kessenichb9197c82019-08-11 07:41:45 -06007866#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007867 // Decode the return types that were structures
7868 switch (op) {
7869 case glslang::EOpAddCarry:
7870 case glslang::EOpSubBorrow:
7871 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7872 id = builder.createCompositeExtract(id, typeId0, 0);
7873 break;
7874 case glslang::EOpUMulExtended:
7875 case glslang::EOpIMulExtended:
7876 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7877 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7878 break;
7879 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007880 {
7881 assert(operands.size() == 2);
7882 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7883 // "exp" is floating-point type (from HLSL intrinsic)
7884 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7885 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7886 builder.createStore(member1, operands[1]);
7887 } else
7888 // "exp" is integer type (from GLSL built-in function)
7889 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7890 id = builder.createCompositeExtract(id, typeId0, 0);
7891 }
John Kessenich55e7d112015-11-15 21:33:39 -07007892 break;
7893 default:
7894 break;
7895 }
John Kessenichb9197c82019-08-11 07:41:45 -06007896#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007897
John Kessenich32cfd492016-02-02 12:37:46 -07007898 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007899}
7900
Rex Xu9d93a232016-05-05 12:30:44 +08007901// Intrinsics with no arguments (or no return value, and no precision).
7902spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007903{
Jeff Bolz36831c92018-09-05 10:11:41 -05007904 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007905 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7906 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007907
7908 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007909 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007910 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007911 if (glslangIntermediate->usingVulkanMemoryModel()) {
7912 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7913 spv::MemorySemanticsOutputMemoryKHRMask |
7914 spv::MemorySemanticsAcquireReleaseMask);
7915 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7916 } else {
7917 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7918 }
John Kessenich82979362017-12-11 04:02:24 -07007919 } else {
7920 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7921 spv::MemorySemanticsWorkgroupMemoryMask |
7922 spv::MemorySemanticsAcquireReleaseMask);
7923 }
John Kessenich140f3df2015-06-26 16:58:36 -06007924 return 0;
7925 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007926 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7927 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007928 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007929 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007930 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7931 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007932 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007933 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007934 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7935 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007936 return 0;
7937 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007938 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7939 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007940 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007941#ifndef GLSLANG_WEB
7942 case glslang::EOpMemoryBarrierAtomicCounter:
7943 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7944 spv::MemorySemanticsAcquireReleaseMask);
7945 return 0;
7946 case glslang::EOpMemoryBarrierImage:
7947 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7948 spv::MemorySemanticsAcquireReleaseMask);
7949 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007950 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007951 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007952 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007953 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007954 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007955 case glslang::EOpDeviceMemoryBarrier:
7956 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7957 spv::MemorySemanticsImageMemoryMask |
7958 spv::MemorySemanticsAcquireReleaseMask);
7959 return 0;
7960 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7961 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7962 spv::MemorySemanticsImageMemoryMask |
7963 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007964 return 0;
7965 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007966 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7967 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007968 return 0;
7969 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007970 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7971 spv::MemorySemanticsWorkgroupMemoryMask |
7972 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007973 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007974 case glslang::EOpSubgroupBarrier:
7975 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7976 spv::MemorySemanticsAcquireReleaseMask);
7977 return spv::NoResult;
7978 case glslang::EOpSubgroupMemoryBarrier:
7979 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7980 spv::MemorySemanticsAcquireReleaseMask);
7981 return spv::NoResult;
7982 case glslang::EOpSubgroupMemoryBarrierBuffer:
7983 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7984 spv::MemorySemanticsAcquireReleaseMask);
7985 return spv::NoResult;
7986 case glslang::EOpSubgroupMemoryBarrierImage:
7987 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7988 spv::MemorySemanticsAcquireReleaseMask);
7989 return spv::NoResult;
7990 case glslang::EOpSubgroupMemoryBarrierShared:
7991 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7992 spv::MemorySemanticsAcquireReleaseMask);
7993 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007994
7995 case glslang::EOpEmitVertex:
7996 builder.createNoResultOp(spv::OpEmitVertex);
7997 return 0;
7998 case glslang::EOpEndPrimitive:
7999 builder.createNoResultOp(spv::OpEndPrimitive);
8000 return 0;
8001
John Kessenich66011cb2018-03-06 16:12:04 -07008002 case glslang::EOpSubgroupElect: {
8003 std::vector<spv::Id> operands;
8004 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8005 }
Rex Xu9d93a232016-05-05 12:30:44 +08008006 case glslang::EOpTime:
8007 {
8008 std::vector<spv::Id> args; // Dummy arguments
8009 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8010 return builder.setPrecision(id, precision);
8011 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008012 case glslang::EOpIgnoreIntersection:
8013 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008014 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008015 case glslang::EOpTerminateRay:
8016 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008017 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008018 case glslang::EOpRayQueryInitialize:
8019 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8020 return 0;
8021 case glslang::EOpRayQueryTerminate:
8022 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8023 return 0;
8024 case glslang::EOpRayQueryGenerateIntersection:
8025 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8026 return 0;
8027 case glslang::EOpRayQueryConfirmIntersection:
8028 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8029 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008030 case glslang::EOpBeginInvocationInterlock:
8031 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8032 return 0;
8033 case glslang::EOpEndInvocationInterlock:
8034 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8035 return 0;
8036
Jeff Bolzba6170b2019-07-01 09:23:23 -05008037 case glslang::EOpIsHelperInvocation:
8038 {
8039 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008040 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8041 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8042 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008043 }
8044
amhagan91fb0092019-07-10 21:14:38 -04008045 case glslang::EOpReadClockSubgroupKHR: {
8046 std::vector<spv::Id> args;
8047 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8048 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8049 builder.addCapability(spv::CapabilityShaderClockKHR);
8050 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8051 }
8052
8053 case glslang::EOpReadClockDeviceKHR: {
8054 std::vector<spv::Id> args;
8055 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8056 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8057 builder.addCapability(spv::CapabilityShaderClockKHR);
8058 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8059 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008060#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008061 default:
John Kessenich155d3512019-08-08 23:29:20 -06008062 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008063 }
John Kessenich155d3512019-08-08 23:29:20 -06008064
8065 logger->missingFunctionality("unknown operation with no arguments");
8066
8067 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008068}
8069
8070spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8071{
John Kessenich2f273362015-07-18 22:34:27 -06008072 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008073 spv::Id id;
8074 if (symbolValues.end() != iter) {
8075 id = iter->second;
8076 return id;
8077 }
8078
8079 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008080 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008081 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008082 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008083 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008084 if (forcedType.second != spv::NoType)
8085 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008086
Rex Xuc884b4a2016-06-29 15:03:44 +08008087 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008088 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8089 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8090 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008091#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008092 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008093 if (symbol->getQualifier().hasComponent())
8094 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8095 if (symbol->getQualifier().hasIndex())
8096 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008097#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008098 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008099 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008100 // atomic counters use this:
8101 if (symbol->getQualifier().hasOffset())
8102 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008103 }
8104
scygan2c864272016-05-18 18:09:17 +02008105 if (symbol->getQualifier().hasLocation())
8106 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008107 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008108 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008109 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008110 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008111 }
John Kessenich140f3df2015-06-26 16:58:36 -06008112 if (symbol->getQualifier().hasSet())
8113 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008114 else if (IsDescriptorResource(symbol->getType())) {
8115 // default to 0
8116 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8117 }
John Kessenich140f3df2015-06-26 16:58:36 -06008118 if (symbol->getQualifier().hasBinding())
8119 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008120 else if (IsDescriptorResource(symbol->getType())) {
8121 // default to 0
8122 builder.addDecoration(id, spv::DecorationBinding, 0);
8123 }
John Kessenich6c292d32016-02-15 20:58:50 -07008124 if (symbol->getQualifier().hasAttachment())
8125 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008126 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008127 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008128 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008129 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008130 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8131 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8132 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8133 }
8134 if (symbol->getQualifier().hasXfbOffset())
8135 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008136 }
8137
John Kessenichb9197c82019-08-11 07:41:45 -06008138 // add built-in variable decoration
8139 if (builtIn != spv::BuiltInMax) {
8140 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8141 }
8142
8143#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008144 if (symbol->getType().isImage()) {
8145 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008146 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8147 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008148 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008149 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008150 }
8151
John Kessenich5611c6d2018-04-05 11:25:02 -06008152 // nonuniform
8153 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8154
chaoc0ad6a4e2016-12-19 16:29:34 -08008155 if (builtIn == spv::BuiltInSampleMask) {
8156 spv::Decoration decoration;
8157 // GL_NV_sample_mask_override_coverage extension
8158 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008159 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008160 else
8161 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008162 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008163 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008164 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008165 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8166 }
8167 }
chaoc771d89f2017-01-13 01:10:53 -08008168 else if (builtIn == spv::BuiltInLayer) {
8169 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008170 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008171 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008172 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8173 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8174 }
John Kessenichb41bff62017-08-11 13:07:17 -06008175 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008176 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8177 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008178 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8179 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8180 }
8181 }
8182
chaoc6e5acae2016-12-20 13:28:52 -08008183 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008184 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008185 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008186 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8187 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008188 if (symbol->getQualifier().pervertexNV) {
8189 builder.addDecoration(id, spv::DecorationPerVertexNV);
8190 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8191 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8192 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008193
John Kessenich5d610ee2018-03-07 18:05:55 -07008194 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8195 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8196 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8197 symbol->getType().getQualifier().semanticName);
8198 }
8199
John Kessenich7015bd62019-08-01 03:28:08 -06008200 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008201 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8202 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008203 }
John Kessenichb9197c82019-08-11 07:41:45 -06008204#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008205
John Kessenich140f3df2015-06-26 16:58:36 -06008206 return id;
8207}
8208
John Kessenicha28f7a72019-08-06 07:00:58 -06008209#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008210// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8211void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8212{
8213 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008214 if (qualifier.perPrimitiveNV) {
8215 // Need to add capability/extension for fragment shader.
8216 // Mesh shader already adds this by default.
8217 if (glslangIntermediate->getStage() == EShLangFragment) {
8218 builder.addCapability(spv::CapabilityMeshShadingNV);
8219 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8220 }
Chao Chen3c366992018-09-19 11:41:59 -07008221 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008222 }
Chao Chen3c366992018-09-19 11:41:59 -07008223 if (qualifier.perViewNV)
8224 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8225 if (qualifier.perTaskNV)
8226 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8227 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008228 if (qualifier.perPrimitiveNV) {
8229 // Need to add capability/extension for fragment shader.
8230 // Mesh shader already adds this by default.
8231 if (glslangIntermediate->getStage() == EShLangFragment) {
8232 builder.addCapability(spv::CapabilityMeshShadingNV);
8233 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8234 }
Chao Chen3c366992018-09-19 11:41:59 -07008235 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008236 }
Chao Chen3c366992018-09-19 11:41:59 -07008237 if (qualifier.perViewNV)
8238 builder.addDecoration(id, spv::DecorationPerViewNV);
8239 if (qualifier.perTaskNV)
8240 builder.addDecoration(id, spv::DecorationPerTaskNV);
8241 }
8242}
8243#endif
8244
John Kessenich55e7d112015-11-15 21:33:39 -07008245// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008246// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008247//
8248// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8249//
8250// Recursively walk the nodes. The nodes form a tree whose leaves are
8251// regular constants, which themselves are trees that createSpvConstant()
8252// recursively walks. So, this function walks the "top" of the tree:
8253// - emit specialization constant-building instructions for specConstant
8254// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008255spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008256{
John Kessenich7cc0e282016-03-20 00:46:02 -06008257 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008258
qining4f4bb812016-04-03 23:55:17 -04008259 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008260 if (! node.getQualifier().specConstant) {
8261 // hand off to the non-spec-constant path
8262 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8263 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008264 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8265 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8266 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008267 }
8268
8269 // We now know we have a specialization constant to build
8270
John Kessenichd94c0032016-05-30 19:29:40 -06008271 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008272 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8273 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8274 std::vector<spv::Id> dimConstId;
8275 for (int dim = 0; dim < 3; ++dim) {
8276 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8277 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008278 if (specConst) {
8279 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8280 glslangIntermediate->getLocalSizeSpecId(dim));
8281 }
qining4f4bb812016-04-03 23:55:17 -04008282 }
8283 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8284 }
8285
8286 // An AST node labelled as specialization constant should be a symbol node.
8287 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8288 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008289 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008290 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008291 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8292 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8293 // will set the builder into spec constant op instruction generating mode.
8294 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008295 result = accessChainLoad(sub_tree->getType());
8296 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008297 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008298 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008299 } else {
8300 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008301 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008302 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008303 builder.addName(result, sn->getName().c_str());
8304 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008305 }
qining4f4bb812016-04-03 23:55:17 -04008306
8307 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8308 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008309 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008310 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008311}
8312
John Kessenich140f3df2015-06-26 16:58:36 -06008313// Use 'consts' as the flattened glslang source of scalar constants to recursively
8314// build the aggregate SPIR-V constant.
8315//
8316// If there are not enough elements present in 'consts', 0 will be substituted;
8317// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8318//
John Kessenich8985fc92020-03-03 10:25:07 -07008319spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8320 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008321{
8322 // vector of constants for SPIR-V
8323 std::vector<spv::Id> spvConsts;
8324
8325 // Type is used for struct and array constants
8326 spv::Id typeId = convertGlslangToSpvType(glslangType);
8327
8328 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008329 glslang::TType elementType(glslangType, 0);
8330 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008331 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008332 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008333 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008334 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008335 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008336 } else if (glslangType.isCoopMat()) {
8337 glslang::TType componentType(glslangType.getBasicType());
8338 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008339 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008340 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8341 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008342 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008343 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008344 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8345 bool zero = nextConst >= consts.size();
8346 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008347 case glslang::EbtInt:
8348 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8349 break;
8350 case glslang::EbtUint:
8351 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8352 break;
8353 case glslang::EbtFloat:
8354 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8355 break;
8356 case glslang::EbtBool:
8357 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8358 break;
8359#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008360 case glslang::EbtInt8:
8361 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8362 break;
8363 case glslang::EbtUint8:
8364 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8365 break;
8366 case glslang::EbtInt16:
8367 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8368 break;
8369 case glslang::EbtUint16:
8370 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8371 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008372 case glslang::EbtInt64:
8373 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8374 break;
8375 case glslang::EbtUint64:
8376 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8377 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008378 case glslang::EbtDouble:
8379 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8380 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008381 case glslang::EbtFloat16:
8382 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8383 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008384#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008385 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008386 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008387 break;
8388 }
8389 ++nextConst;
8390 }
8391 } else {
8392 // we have a non-aggregate (scalar) constant
8393 bool zero = nextConst >= consts.size();
8394 spv::Id scalar = 0;
8395 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008396 case glslang::EbtInt:
8397 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8398 break;
8399 case glslang::EbtUint:
8400 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8401 break;
8402 case glslang::EbtFloat:
8403 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8404 break;
8405 case glslang::EbtBool:
8406 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8407 break;
8408#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008409 case glslang::EbtInt8:
8410 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8411 break;
8412 case glslang::EbtUint8:
8413 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8414 break;
8415 case glslang::EbtInt16:
8416 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8417 break;
8418 case glslang::EbtUint16:
8419 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8420 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008421 case glslang::EbtInt64:
8422 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8423 break;
8424 case glslang::EbtUint64:
8425 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8426 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008427 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008428 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008429 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008430 case glslang::EbtFloat16:
8431 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8432 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008433 case glslang::EbtReference:
8434 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8435 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8436 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008437#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008438 case glslang::EbtString:
8439 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8440 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008441 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008442 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008443 break;
8444 }
8445 ++nextConst;
8446 return scalar;
8447 }
8448
8449 return builder.makeCompositeConstant(typeId, spvConsts);
8450}
8451
John Kessenich7c1aa102015-10-15 13:29:11 -06008452// Return true if the node is a constant or symbol whose reading has no
8453// non-trivial observable cost or effect.
8454bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8455{
8456 // don't know what this is
8457 if (node == nullptr)
8458 return false;
8459
8460 // a constant is safe
8461 if (node->getAsConstantUnion() != nullptr)
8462 return true;
8463
8464 // not a symbol means non-trivial
8465 if (node->getAsSymbolNode() == nullptr)
8466 return false;
8467
8468 // a symbol, depends on what's being read
8469 switch (node->getType().getQualifier().storage) {
8470 case glslang::EvqTemporary:
8471 case glslang::EvqGlobal:
8472 case glslang::EvqIn:
8473 case glslang::EvqInOut:
8474 case glslang::EvqConst:
8475 case glslang::EvqConstReadOnly:
8476 case glslang::EvqUniform:
8477 return true;
8478 default:
8479 return false;
8480 }
qining25262b32016-05-06 17:25:16 -04008481}
John Kessenich7c1aa102015-10-15 13:29:11 -06008482
8483// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008484// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008485// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008486// Return true if trivial.
8487bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8488{
8489 if (node == nullptr)
8490 return false;
8491
John Kessenich84cc15f2017-05-24 16:44:47 -06008492 // count non scalars as trivial, as well as anything coming from HLSL
8493 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008494 return true;
8495
John Kessenich7c1aa102015-10-15 13:29:11 -06008496 // symbols and constants are trivial
8497 if (isTrivialLeaf(node))
8498 return true;
8499
8500 // otherwise, it needs to be a simple operation or one or two leaf nodes
8501
8502 // not a simple operation
8503 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8504 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8505 if (binaryNode == nullptr && unaryNode == nullptr)
8506 return false;
8507
8508 // not on leaf nodes
8509 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8510 return false;
8511
8512 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8513 return false;
8514 }
8515
8516 switch (node->getAsOperator()->getOp()) {
8517 case glslang::EOpLogicalNot:
8518 case glslang::EOpConvIntToBool:
8519 case glslang::EOpConvUintToBool:
8520 case glslang::EOpConvFloatToBool:
8521 case glslang::EOpConvDoubleToBool:
8522 case glslang::EOpEqual:
8523 case glslang::EOpNotEqual:
8524 case glslang::EOpLessThan:
8525 case glslang::EOpGreaterThan:
8526 case glslang::EOpLessThanEqual:
8527 case glslang::EOpGreaterThanEqual:
8528 case glslang::EOpIndexDirect:
8529 case glslang::EOpIndexDirectStruct:
8530 case glslang::EOpLogicalXor:
8531 case glslang::EOpAny:
8532 case glslang::EOpAll:
8533 return true;
8534 default:
8535 return false;
8536 }
8537}
8538
8539// Emit short-circuiting code, where 'right' is never evaluated unless
8540// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008541spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8542 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008543{
8544 spv::Id boolTypeId = builder.makeBoolType();
8545
8546 // emit left operand
8547 builder.clearAccessChain();
8548 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008549 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008550
8551 // Operands to accumulate OpPhi operands
8552 std::vector<spv::Id> phiOperands;
8553 // accumulate left operand's phi information
8554 phiOperands.push_back(leftId);
8555 phiOperands.push_back(builder.getBuildPoint()->getId());
8556
8557 // Make the two kinds of operation symmetric with a "!"
8558 // || => emit "if (! left) result = right"
8559 // && => emit "if ( left) result = right"
8560 //
8561 // TODO: this runtime "not" for || could be avoided by adding functionality
8562 // to 'builder' to have an "else" without an "then"
8563 if (op == glslang::EOpLogicalOr)
8564 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8565
8566 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008567 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008568
8569 // emit right operand as the "then" part of the "if"
8570 builder.clearAccessChain();
8571 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008572 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008573
8574 // accumulate left operand's phi information
8575 phiOperands.push_back(rightId);
8576 phiOperands.push_back(builder.getBuildPoint()->getId());
8577
8578 // finish the "if"
8579 ifBuilder.makeEndIf();
8580
8581 // phi together the two results
8582 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8583}
8584
John Kessenicha28f7a72019-08-06 07:00:58 -06008585#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008586// Return type Id of the imported set of extended instructions corresponds to the name.
8587// Import this set if it has not been imported yet.
8588spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8589{
8590 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8591 return extBuiltinMap[name];
8592 else {
Rex Xu51596642016-09-21 18:56:12 +08008593 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008594 spv::Id extBuiltins = builder.import(name);
8595 extBuiltinMap[name] = extBuiltins;
8596 return extBuiltins;
8597 }
8598}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008599#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008600
John Kessenich140f3df2015-06-26 16:58:36 -06008601}; // end anonymous namespace
8602
8603namespace glslang {
8604
John Kessenich68d78fd2015-07-12 19:28:10 -06008605void GetSpirvVersion(std::string& version)
8606{
John Kessenich9e55f632015-07-15 10:03:39 -06008607 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008608 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008609 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008610 version = buf;
8611}
8612
John Kessenicha372a3e2017-11-02 22:32:14 -06008613// For low-order part of the generator's magic number. Bump up
8614// when there is a change in the style (e.g., if SSA form changes,
8615// or a different instruction sequence to do something gets used).
8616int GetSpirvGeneratorVersion()
8617{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008618 // return 1; // start
8619 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008620 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008621 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008622 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008623 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8624 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008625 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8626 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008627}
8628
John Kessenich140f3df2015-06-26 16:58:36 -06008629// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008630void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008631{
8632 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008633 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008634 if (out.fail())
8635 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008636 for (int i = 0; i < (int)spirv.size(); ++i) {
8637 unsigned int word = spirv[i];
8638 out.write((const char*)&word, 4);
8639 }
8640 out.close();
8641}
8642
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008643// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008644void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008645{
John Kessenich155d3512019-08-08 23:29:20 -06008646#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008647 std::ofstream out;
8648 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008649 if (out.fail())
8650 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008651 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008652 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008653 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008654 if (varName != nullptr) {
8655 out << "\t #pragma once" << std::endl;
8656 out << "const uint32_t " << varName << "[] = {" << std::endl;
8657 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008658 const int WORDS_PER_LINE = 8;
8659 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8660 out << "\t";
8661 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8662 const unsigned int word = spirv[i + j];
8663 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8664 if (i + j + 1 < (int)spirv.size()) {
8665 out << ",";
8666 }
8667 }
8668 out << std::endl;
8669 }
Flavio15017db2017-02-15 14:29:33 -08008670 if (varName != nullptr) {
8671 out << "};";
8672 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008673 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008674#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008675}
8676
John Kessenich140f3df2015-06-26 16:58:36 -06008677//
8678// Set up the glslang traversal
8679//
John Kessenich4e11b612018-08-30 16:56:59 -06008680void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008681{
Lei Zhang17535f72016-05-04 15:55:59 -04008682 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008683 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008684}
8685
John Kessenich4e11b612018-08-30 16:56:59 -06008686void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008687 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008688{
John Kessenich140f3df2015-06-26 16:58:36 -06008689 TIntermNode* root = intermediate.getTreeRoot();
8690
8691 if (root == 0)
8692 return;
8693
John Kessenich4e11b612018-08-30 16:56:59 -06008694 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008695 if (options == nullptr)
8696 options = &defaultOptions;
8697
John Kessenich4e11b612018-08-30 16:56:59 -06008698 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008699
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008700 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008701 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008702 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008703 it.dumpSpv(spirv);
8704
GregFfb03a552018-03-29 11:49:14 -06008705#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008706 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8707 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008708 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8709 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008710 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008711 prelegalization = false;
8712 }
John Kessenich717c80a2018-08-23 15:17:10 -06008713
John Kessenich4e11b612018-08-30 16:56:59 -06008714 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008715 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008716
John Kessenich717c80a2018-08-23 15:17:10 -06008717 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008718 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008719
GregFcd1f1692017-09-21 18:40:22 -06008720#endif
8721
John Kessenich4e11b612018-08-30 16:56:59 -06008722 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008723}
8724
8725}; // end namespace glslang