blob: 81aacd11216b91758283c0827162ee9f42d591c4 [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"
Ben Claytonfbe9a232020-06-17 11:17:19 +010059
60// Build-time generated includes
61#include "glslang/build_info.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060094 public:
95 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
96 precision(precision)
97#ifndef GLSLANG_WEB
98 ,
99 noContraction(noContraction),
100 nonUniform(nonUniform)
101#endif
102 { }
103
John Kessenichead86222018-03-28 18:01:20 -0600104 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600105
106#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400107 void addNoContraction(spv::Builder&, spv::Id) const { }
108 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600109#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400110 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
111 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600112 protected:
113 spv::Decoration noContraction;
114 spv::Decoration nonUniform;
115#endif
116
John Kessenichead86222018-03-28 18:01:20 -0600117};
118
119} // namespace
qining4c912612016-04-01 10:35:16 -0400120
John Kessenich140f3df2015-06-26 16:58:36 -0600121//
122// The main holder of information for translating glslang to SPIR-V.
123//
124// Derives from the AST walking base class.
125//
126class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
127public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700128 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
129 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700130 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600131
132 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
133 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
134 void visitConstantUnion(glslang::TIntermConstantUnion*);
135 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
136 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
137 void visitSymbol(glslang::TIntermSymbol* symbol);
138 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
139 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
140 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
141
John Kessenichfca82622016-11-26 13:23:20 -0700142 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700143 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600144
145protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700146 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
147 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
148
Rex Xu17ff3432016-10-14 17:41:45 +0800149 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800150 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600151 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
greg-lunarg639f5462020-11-12 11:10:07 -0700152 spv::Decoration TranslateNonUniformDecoration(const spv::Builder::AccessChain::CoherentFlags& coherentFlags);
Jeff Bolz36831c92018-09-05 10:11:41 -0500153 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
154 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
155 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
156 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100157 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700158 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700159 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
160 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700161 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600162 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600163 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600164 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600166 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
167 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
168 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600169 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600170 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600171 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600172 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600173 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
174 glslang::TLayoutPacking, const glslang::TQualifier&);
175 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
176 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700177 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700178 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800179 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600180 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700181 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700182 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
183 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700184 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
185 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100186 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600187
John Kessenich6fccb3c2016-09-19 16:01:41 -0600188 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600189 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600190 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600191 void makeFunctions(const glslang::TIntermSequence&);
192 void makeGlobalInitializers(const glslang::TIntermSequence&);
Daniel Kochffccefd2020-11-23 15:41:27 -0500193 void collectRayTracingLinkerObjects();
John Kessenich140f3df2015-06-26 16:58:36 -0600194 void visitFunctions(const glslang::TIntermSequence&);
195 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700196 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
197 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600198 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
199 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600200 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
201
John Kessenichead86222018-03-28 18:01:20 -0600202 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
203 glslang::TBasicType typeProxy, bool reduceComparison = true);
204 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
205 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700206 glslang::TBasicType typeProxy,
207 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600208 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
209 glslang::TBasicType typeProxy);
210 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
211 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600212 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700214 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
215 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
216 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
217 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
218 glslang::TBasicType typeProxy);
219 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
220 spv::Id typeId, std::vector<spv::Id>& operands);
221 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
222 glslang::TBasicType typeProxy);
223 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
224 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800225 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600226 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700227 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400228 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700229 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
230 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600231 bool isTrivialLeaf(const glslang::TIntermTyped* node);
232 bool isTrivial(const glslang::TIntermTyped* node);
233 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800234 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400235 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600236 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500237 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600238
John Kessenich121853f2017-05-31 17:11:16 -0600239 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600241 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700242 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600243 int sequenceDepth;
244
Lei Zhang17535f72016-05-04 15:55:59 -0400245 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400246
John Kessenich140f3df2015-06-26 16:58:36 -0600247 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
248 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700249 bool inEntryPoint;
250 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700251 bool linkageOnly; // true when visiting the set of objects in the AST present only for
252 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700253 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600254 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600255 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600256 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500257 spv::Id nonSemanticDebugPrintf;
Rex Xu77fe62f2021-02-26 17:25:45 +0800258 std::unordered_map<std::string, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600259
Chow93b400f2020-11-12 15:54:16 +0800260 std::unordered_map<long long, spv::Id> symbolValues;
261 std::unordered_set<long long> rValueParameters; // set of formal function parameters passed as rValues,
John Kessenich8985fc92020-03-03 10:25:07 -0700262 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600263 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700264 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700265 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Chow93b400f2020-11-12 15:54:16 +0800266 std::unordered_map<long long, std::vector<int>> memberRemapper;
Roy05a5b532020-01-03 16:21:34 +0800267 // for mapping glslang symbol struct to symbol Id
Chow93b400f2020-11-12 15:54:16 +0800268 std::unordered_map<const glslang::TTypeList*, long long> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700270 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600271 // Map pointee types for EbtReference to their forward pointers
272 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600273 // Type forcing, for when SPIR-V wants a different type than the AST,
274 // requiring local translation to and from SPIR-V type on every access.
275 // Maps <builtin-variable-id -> AST-required-type-id>
276 std::unordered_map<spv::Id, spv::Id> forceType;
Daniel Kochffccefd2020-11-23 15:41:27 -0500277
278 // Used later for generating OpTraceKHR/OpExecuteCallableKHR
279 std::unordered_map<unsigned int, glslang::TIntermSymbol *> locationToSymbol[2];
John Kessenich140f3df2015-06-26 16:58:36 -0600280};
281
282//
283// Helper functions for translating glslang representations to SPIR-V enumerants.
284//
285
286// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700287spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600288{
John Kessenich155d3512019-08-08 23:29:20 -0600289#ifdef GLSLANG_WEB
290 return spv::SourceLanguageESSL;
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -0400291#elif defined(GLSLANG_ANGLE)
292 return spv::SourceLanguageGLSL;
John Kessenich155d3512019-08-08 23:29:20 -0600293#endif
294
John Kessenich66e2faf2016-03-12 18:34:36 -0700295 switch (source) {
296 case glslang::EShSourceGlsl:
297 switch (profile) {
298 case ENoProfile:
299 case ECoreProfile:
300 case ECompatibilityProfile:
301 return spv::SourceLanguageGLSL;
302 case EEsProfile:
303 return spv::SourceLanguageESSL;
304 default:
305 return spv::SourceLanguageUnknown;
306 }
307 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600308 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600309 default:
310 return spv::SourceLanguageUnknown;
311 }
312}
313
314// Translate glslang language (stage) to SPIR-V execution model.
315spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
316{
317 switch (stage) {
318 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600319 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600320 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600321#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600322 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
323 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
324 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400325 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
326 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
327 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
328 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
329 case EShLangMiss: return spv::ExecutionModelMissKHR;
330 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700331 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
332 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
333#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600334 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700335 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600336 return spv::ExecutionModelFragment;
337 }
338}
339
John Kessenich140f3df2015-06-26 16:58:36 -0600340// Translate glslang sampler type to SPIR-V dimensionality.
341spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
342{
343 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700344 case glslang::Esd1D: return spv::Dim1D;
345 case glslang::Esd2D: return spv::Dim2D;
346 case glslang::Esd3D: return spv::Dim3D;
347 case glslang::EsdCube: return spv::DimCube;
348 case glslang::EsdRect: return spv::DimRect;
349 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700350 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600351 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700352 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600353 return spv::Dim2D;
354 }
355}
356
John Kessenichf6640762016-08-01 19:44:00 -0600357// Translate glslang precision to SPIR-V precision decorations.
358spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600359{
John Kessenichf6640762016-08-01 19:44:00 -0600360 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700361 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600362 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 default:
364 return spv::NoPrecision;
365 }
366}
367
John Kessenichf6640762016-08-01 19:44:00 -0600368// Translate glslang type to SPIR-V precision decorations.
369spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
370{
371 return TranslatePrecisionDecoration(type.getQualifier().precision);
372}
373
John Kessenich140f3df2015-06-26 16:58:36 -0600374// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600375spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600376{
377 if (type.getBasicType() == glslang::EbtBlock) {
378 switch (type.getQualifier().storage) {
379 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600380 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 case glslang::EvqVaryingIn: return spv::DecorationBlock;
382 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Caio Marcelo de Oliveira Filho4bfbf622020-06-02 16:58:51 -0700383 case glslang::EvqShared: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600384#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400385 case glslang::EvqPayload: return spv::DecorationBlock;
386 case glslang::EvqPayloadIn: return spv::DecorationBlock;
387 case glslang::EvqHitAttr: return spv::DecorationBlock;
388 case glslang::EvqCallableData: return spv::DecorationBlock;
389 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700390#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600391 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700392 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600393 break;
394 }
395 }
396
John Kessenich4016e382016-07-15 11:53:56 -0600397 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600398}
399
Rex Xu1da878f2016-02-21 20:59:01 +0800400// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700401void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
402 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800403{
Jeff Bolz36831c92018-09-05 10:11:41 -0500404 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600405 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500406 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600407 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500408 memory.push_back(spv::DecorationVolatile);
409 memory.push_back(spv::DecorationCoherent);
410 }
John Kessenich14b85d32018-06-04 15:36:03 -0600411 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600412 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800413 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600414 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800415 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600416 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800417 memory.push_back(spv::DecorationNonReadable);
418}
419
John Kessenich140f3df2015-06-26 16:58:36 -0600420// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700421spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600422{
423 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700424 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600425 case glslang::ElmRowMajor:
426 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700427 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700429 default:
430 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600431 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600432 }
433 } else {
434 switch (type.getBasicType()) {
435 default:
John Kessenich4016e382016-07-15 11:53:56 -0600436 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600437 break;
438 case glslang::EbtBlock:
439 switch (type.getQualifier().storage) {
Caio Marcelo de Oliveira Filho4bfbf622020-06-02 16:58:51 -0700440 case glslang::EvqShared:
John Kessenich140f3df2015-06-26 16:58:36 -0600441 case glslang::EvqUniform:
442 case glslang::EvqBuffer:
443 switch (type.getQualifier().layoutPacking) {
444 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600445 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
446 default:
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600448 }
449 case glslang::EvqVaryingIn:
450 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700451 if (type.getQualifier().isTaskMemory()) {
452 switch (type.getQualifier().layoutPacking) {
453 case glslang::ElpShared: return spv::DecorationGLSLShared;
454 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
455 default: break;
456 }
457 } else {
458 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
459 }
John Kessenich4016e382016-07-15 11:53:56 -0600460 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600461#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400462 case glslang::EvqPayload:
463 case glslang::EvqPayloadIn:
464 case glslang::EvqHitAttr:
465 case glslang::EvqCallableData:
466 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700467 return spv::DecorationMax;
468#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600469 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700470 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600471 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600472 }
473 }
474 }
475}
476
477// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600478// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700479// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800480spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600481{
Rex Xubbceed72016-05-21 09:40:44 +0800482 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700483 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600484 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600485 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700486 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700487 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600488 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600489 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800490 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800491 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800492 }
Rex Xubbceed72016-05-21 09:40:44 +0800493 else
John Kessenich4016e382016-07-15 11:53:56 -0600494 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800495}
496
497// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600498// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800499// should be applied.
500spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
501{
John Kessenichb9197c82019-08-11 07:41:45 -0600502 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600503 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600504#ifndef GLSLANG_WEB
505 else if (qualifier.patch)
506 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700507 else if (qualifier.sample) {
508 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600509 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600510 }
511#endif
512
513 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600514}
515
John Kessenich92187592016-02-01 13:45:25 -0700516// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700517spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600518{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700519 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600520 return spv::DecorationInvariant;
521 else
John Kessenich4016e382016-07-15 11:53:56 -0600522 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600523}
524
qining9220dbb2016-05-04 17:34:38 -0400525// If glslang type is noContraction, return SPIR-V NoContraction decoration.
526spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
527{
John Kessenichb9197c82019-08-11 07:41:45 -0600528#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600529 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400530 return spv::DecorationNoContraction;
531 else
John Kessenichb9197c82019-08-11 07:41:45 -0600532#endif
John Kessenich4016e382016-07-15 11:53:56 -0600533 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400534}
535
John Kessenich5611c6d2018-04-05 11:25:02 -0600536// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
537spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
538{
John Kessenichb9197c82019-08-11 07:41:45 -0600539#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600540 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600541 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600542 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
543 return spv::DecorationNonUniformEXT;
544 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600545#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600546 return spv::DecorationMax;
547}
548
greg-lunarg639f5462020-11-12 11:10:07 -0700549// If lvalue flags contains nonUniform, return SPIR-V NonUniform decoration.
550spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(
551 const spv::Builder::AccessChain::CoherentFlags& coherentFlags)
552{
553#ifndef GLSLANG_WEB
554 if (coherentFlags.isNonUniform()) {
555 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
556 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
557 return spv::DecorationNonUniformEXT;
558 } else
559#endif
560 return spv::DecorationMax;
561}
562
John Kessenichb9197c82019-08-11 07:41:45 -0600563spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
564 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500565{
Jeff Bolz36831c92018-09-05 10:11:41 -0500566 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600567
568#ifndef GLSLANG_WEB
569 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
570 return mask;
571
Daniel Kochdb32b242020-03-17 20:42:47 -0400572 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500573 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
574 spv::MemoryAccessMakePointerVisibleKHRMask;
575 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400576
Jeff Bolz36831c92018-09-05 10:11:41 -0500577 if (coherentFlags.nonprivate) {
578 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
579 }
580 if (coherentFlags.volatil) {
581 mask = mask | spv::MemoryAccessVolatileMask;
582 }
583 if (mask != spv::MemoryAccessMaskNone) {
584 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
585 }
John Kessenichb9197c82019-08-11 07:41:45 -0600586#endif
587
Jeff Bolz36831c92018-09-05 10:11:41 -0500588 return mask;
589}
590
John Kessenichb9197c82019-08-11 07:41:45 -0600591spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
592 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500593{
Jeff Bolz36831c92018-09-05 10:11:41 -0500594 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600595
596#ifndef GLSLANG_WEB
597 if (!glslangIntermediate->usingVulkanMemoryModel())
598 return mask;
599
Jeff Bolz36831c92018-09-05 10:11:41 -0500600 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400601 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500602 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
603 spv::ImageOperandsMakeTexelVisibleKHRMask;
604 }
605 if (coherentFlags.nonprivate) {
606 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
607 }
608 if (coherentFlags.volatil) {
609 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
610 }
611 if (mask != spv::ImageOperandsMaskNone) {
612 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
613 }
John Kessenichb9197c82019-08-11 07:41:45 -0600614#endif
615
Jeff Bolz36831c92018-09-05 10:11:41 -0500616 return mask;
617}
618
619spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
620{
John Kessenichb9197c82019-08-11 07:41:45 -0600621 spv::Builder::AccessChain::CoherentFlags flags = {};
622#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500623 flags.coherent = type.getQualifier().coherent;
624 flags.devicecoherent = type.getQualifier().devicecoherent;
625 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
626 // shared variables are implicitly workgroupcoherent in GLSL.
627 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
628 type.getQualifier().storage == glslang::EvqShared;
629 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400630 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600631 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500632 // *coherent variables are implicitly nonprivate in GLSL
633 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400634 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600635 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500636 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600637#endif
greg-lunarg639f5462020-11-12 11:10:07 -0700638 flags.nonUniform = type.getQualifier().nonUniform;
Jeff Bolz36831c92018-09-05 10:11:41 -0500639 return flags;
640}
641
John Kessenichb9197c82019-08-11 07:41:45 -0600642spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
643 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500644{
John Kessenichb9197c82019-08-11 07:41:45 -0600645 spv::Scope scope = spv::ScopeMax;
646
647#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600648 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500649 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
650 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
651 } else if (coherentFlags.devicecoherent) {
652 scope = spv::ScopeDevice;
653 } else if (coherentFlags.queuefamilycoherent) {
654 scope = spv::ScopeQueueFamilyKHR;
655 } else if (coherentFlags.workgroupcoherent) {
656 scope = spv::ScopeWorkgroup;
657 } else if (coherentFlags.subgroupcoherent) {
658 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400659 } else if (coherentFlags.shadercallcoherent) {
660 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500661 }
662 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
663 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
664 }
John Kessenichb9197c82019-08-11 07:41:45 -0600665#endif
666
Jeff Bolz36831c92018-09-05 10:11:41 -0500667 return scope;
668}
669
David Netoa901ffe2016-06-08 14:11:40 +0100670// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
671// associated capabilities when required. For some built-in variables, a capability
672// is generated only when using the variable in an executable instruction, but not when
673// just declaring a struct member variable with it. This is true for PointSize,
674// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700675spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
676 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600677{
678 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700679 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600680#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600681 // Defer adding the capability until the built-in is actually used.
682 if (! memberDeclaration) {
683 switch (glslangIntermediate->getStage()) {
684 case EShLangGeometry:
685 builder.addCapability(spv::CapabilityGeometryPointSize);
686 break;
687 case EShLangTessControl:
688 case EShLangTessEvaluation:
689 builder.addCapability(spv::CapabilityTessellationPointSize);
690 break;
691 default:
692 break;
693 }
John Kessenich92187592016-02-01 13:45:25 -0700694 }
John Kessenich155d3512019-08-08 23:29:20 -0600695#endif
John Kessenich92187592016-02-01 13:45:25 -0700696 return spv::BuiltInPointSize;
697
John Kessenicha28f7a72019-08-06 07:00:58 -0600698 case glslang::EbvPosition: return spv::BuiltInPosition;
699 case glslang::EbvVertexId: return spv::BuiltInVertexId;
700 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
701 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
702 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
703
704 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
705 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
706 case glslang::EbvFace: return spv::BuiltInFrontFacing;
707 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
708
John Kessenich3dd1ce52019-10-17 07:08:40 -0600709 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
710 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
711 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
712 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
713 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
714 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
715
John Kessenicha28f7a72019-08-06 07:00:58 -0600716#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600717 // These *Distance capabilities logically belong here, but if the member is declared and
718 // then never used, consumers of SPIR-V prefer the capability not be declared.
719 // They are now generated when used, rather than here when declared.
720 // Potentially, the specification should be more clear what the minimum
721 // use needed is to trigger the capability.
722 //
John Kessenich92187592016-02-01 13:45:25 -0700723 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100724 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800725 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700726 return spv::BuiltInClipDistance;
727
728 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100729 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800730 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700731 return spv::BuiltInCullDistance;
732
733 case glslang::EbvViewportIndex:
David Netofb53f832020-11-12 15:00:16 -0500734 if (glslangIntermediate->getStage() == EShLangGeometry ||
735 glslangIntermediate->getStage() == EShLangFragment) {
736 builder.addCapability(spv::CapabilityMultiViewport);
737 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600738 if (glslangIntermediate->getStage() == EShLangVertex ||
739 glslangIntermediate->getStage() == EShLangTessControl ||
740 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800741
Sidney Just56350ca2020-11-02 11:27:40 -0800742 if (builder.getSpvVersion() < spv::Spv_1_5) {
743 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
744 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
745 }
746 else
747 builder.addCapability(spv::CapabilityShaderViewportIndex);
Rex Xu5e317ff2017-03-16 23:02:39 +0800748 }
John Kessenich92187592016-02-01 13:45:25 -0700749 return spv::BuiltInViewportIndex;
750
John Kessenich5e801132016-02-15 11:09:46 -0700751 case glslang::EbvSampleId:
752 builder.addCapability(spv::CapabilitySampleRateShading);
753 return spv::BuiltInSampleId;
754
755 case glslang::EbvSamplePosition:
756 builder.addCapability(spv::CapabilitySampleRateShading);
757 return spv::BuiltInSamplePosition;
758
759 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700760 return spv::BuiltInSampleMask;
761
John Kessenich78a45572016-07-08 14:05:15 -0600762 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700763 if (glslangIntermediate->getStage() == EShLangMeshNV) {
764 return spv::BuiltInLayer;
765 }
David Netofb53f832020-11-12 15:00:16 -0500766 if (glslangIntermediate->getStage() == EShLangGeometry ||
767 glslangIntermediate->getStage() == EShLangFragment) {
768 builder.addCapability(spv::CapabilityGeometry);
769 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600770 if (glslangIntermediate->getStage() == EShLangVertex ||
771 glslangIntermediate->getStage() == EShLangTessControl ||
772 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800773
Sidney Just56350ca2020-11-02 11:27:40 -0800774 if (builder.getSpvVersion() < spv::Spv_1_5) {
775 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
776 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
777 } else
778 builder.addCapability(spv::CapabilityShaderLayer);
Rex Xu5e317ff2017-03-16 23:02:39 +0800779 }
John Kessenich78a45572016-07-08 14:05:15 -0600780 return spv::BuiltInLayer;
781
John Kessenichda581a22015-10-14 14:10:30 -0600782 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600783 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800784 builder.addCapability(spv::CapabilityDrawParameters);
785 return spv::BuiltInBaseVertex;
786
John Kessenichda581a22015-10-14 14:10:30 -0600787 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600788 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800789 builder.addCapability(spv::CapabilityDrawParameters);
790 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200791
John Kessenichda581a22015-10-14 14:10:30 -0600792 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600793 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800794 builder.addCapability(spv::CapabilityDrawParameters);
795 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200796
797 case glslang::EbvPrimitiveId:
798 if (glslangIntermediate->getStage() == EShLangFragment)
799 builder.addCapability(spv::CapabilityGeometry);
800 return spv::BuiltInPrimitiveId;
801
Rex Xu37cdcee2017-06-29 17:46:34 +0800802 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800803 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
804 builder.addCapability(spv::CapabilityStencilExportEXT);
805 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800806
Chowa315b562020-07-02 15:50:36 +0800807 case glslang::EbvShadingRateKHR:
808 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
809 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
810 return spv::BuiltInShadingRateKHR;
811
812 case glslang::EbvPrimitiveShadingRateKHR:
813 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
814 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
815 return spv::BuiltInPrimitiveShadingRateKHR;
816
John Kessenich140f3df2015-06-26 16:58:36 -0600817 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600818 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
819 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
820 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
821 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600822 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800823
Rex Xu574ab042016-04-14 16:53:07 +0800824 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800825 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800826 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
827 return spv::BuiltInSubgroupSize;
828
Rex Xu574ab042016-04-14 16:53:07 +0800829 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800830 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800831 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
832 return spv::BuiltInSubgroupLocalInvocationId;
833
Rex Xu574ab042016-04-14 16:53:07 +0800834 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800835 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
836 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600837 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800838
Rex Xu574ab042016-04-14 16:53:07 +0800839 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800840 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
841 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600842 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800843
Rex Xu574ab042016-04-14 16:53:07 +0800844 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800845 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
846 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600847 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800848
Rex Xu574ab042016-04-14 16:53:07 +0800849 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800850 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
851 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600852 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800853
Rex Xu574ab042016-04-14 16:53:07 +0800854 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800855 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
856 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600857 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800858
John Kessenich66011cb2018-03-06 16:12:04 -0700859 case glslang::EbvNumSubgroups:
860 builder.addCapability(spv::CapabilityGroupNonUniform);
861 return spv::BuiltInNumSubgroups;
862
863 case glslang::EbvSubgroupID:
864 builder.addCapability(spv::CapabilityGroupNonUniform);
865 return spv::BuiltInSubgroupId;
866
867 case glslang::EbvSubgroupSize2:
868 builder.addCapability(spv::CapabilityGroupNonUniform);
869 return spv::BuiltInSubgroupSize;
870
871 case glslang::EbvSubgroupInvocation2:
872 builder.addCapability(spv::CapabilityGroupNonUniform);
873 return spv::BuiltInSubgroupLocalInvocationId;
874
875 case glslang::EbvSubgroupEqMask2:
876 builder.addCapability(spv::CapabilityGroupNonUniform);
877 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
878 return spv::BuiltInSubgroupEqMask;
879
880 case glslang::EbvSubgroupGeMask2:
881 builder.addCapability(spv::CapabilityGroupNonUniform);
882 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
883 return spv::BuiltInSubgroupGeMask;
884
885 case glslang::EbvSubgroupGtMask2:
886 builder.addCapability(spv::CapabilityGroupNonUniform);
887 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
888 return spv::BuiltInSubgroupGtMask;
889
890 case glslang::EbvSubgroupLeMask2:
891 builder.addCapability(spv::CapabilityGroupNonUniform);
892 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
893 return spv::BuiltInSubgroupLeMask;
894
895 case glslang::EbvSubgroupLtMask2:
896 builder.addCapability(spv::CapabilityGroupNonUniform);
897 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
898 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600899
Rex Xu17ff3432016-10-14 17:41:45 +0800900 case glslang::EbvBaryCoordNoPersp:
901 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
902 return spv::BuiltInBaryCoordNoPerspAMD;
903
904 case glslang::EbvBaryCoordNoPerspCentroid:
905 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
906 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
907
908 case glslang::EbvBaryCoordNoPerspSample:
909 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
910 return spv::BuiltInBaryCoordNoPerspSampleAMD;
911
912 case glslang::EbvBaryCoordSmooth:
913 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
914 return spv::BuiltInBaryCoordSmoothAMD;
915
916 case glslang::EbvBaryCoordSmoothCentroid:
917 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
918 return spv::BuiltInBaryCoordSmoothCentroidAMD;
919
920 case glslang::EbvBaryCoordSmoothSample:
921 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
922 return spv::BuiltInBaryCoordSmoothSampleAMD;
923
924 case glslang::EbvBaryCoordPullModel:
925 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
926 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800927
John Kessenich6c8aaac2017-02-27 01:20:51 -0700928 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600929 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700930 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700931 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700932
933 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600934 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700935 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700936 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700937
Daniel Koch5154db52018-11-26 10:01:58 -0500938 case glslang::EbvFragSizeEXT:
939 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
940 builder.addCapability(spv::CapabilityFragmentDensityEXT);
941 return spv::BuiltInFragSizeEXT;
942
943 case glslang::EbvFragInvocationCountEXT:
944 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
945 builder.addCapability(spv::CapabilityFragmentDensityEXT);
946 return spv::BuiltInFragInvocationCountEXT;
947
chaoc771d89f2017-01-13 01:10:53 -0800948 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800949 if (!memberDeclaration) {
950 builder.addExtension(spv::E_SPV_NV_viewport_array2);
951 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
952 }
chaoc771d89f2017-01-13 01:10:53 -0800953 return spv::BuiltInViewportMaskNV;
954 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800955 if (!memberDeclaration) {
956 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
957 builder.addCapability(spv::CapabilityShaderStereoViewNV);
958 }
chaoc771d89f2017-01-13 01:10:53 -0800959 return spv::BuiltInSecondaryPositionNV;
960 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800961 if (!memberDeclaration) {
962 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
963 builder.addCapability(spv::CapabilityShaderStereoViewNV);
964 }
chaoc771d89f2017-01-13 01:10:53 -0800965 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800966 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800967 if (!memberDeclaration) {
968 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
969 builder.addCapability(spv::CapabilityPerViewAttributesNV);
970 }
chaocdf3956c2017-02-14 14:52:34 -0800971 return spv::BuiltInPositionPerViewNV;
972 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800973 if (!memberDeclaration) {
974 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
975 builder.addCapability(spv::CapabilityPerViewAttributesNV);
976 }
chaocdf3956c2017-02-14 14:52:34 -0800977 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700978 case glslang::EbvFragFullyCoveredNV:
979 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
980 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
981 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700982 case glslang::EbvFragmentSizeNV:
983 builder.addExtension(spv::E_SPV_NV_shading_rate);
984 builder.addCapability(spv::CapabilityShadingRateNV);
985 return spv::BuiltInFragmentSizeNV;
986 case glslang::EbvInvocationsPerPixelNV:
987 builder.addExtension(spv::E_SPV_NV_shading_rate);
988 builder.addCapability(spv::CapabilityShadingRateNV);
989 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700990
Daniel Koch593a4e02019-05-27 16:46:31 -0400991 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400992 case glslang::EbvLaunchId:
993 return spv::BuiltInLaunchIdKHR;
994 case glslang::EbvLaunchSize:
995 return spv::BuiltInLaunchSizeKHR;
996 case glslang::EbvWorldRayOrigin:
997 return spv::BuiltInWorldRayOriginKHR;
998 case glslang::EbvWorldRayDirection:
999 return spv::BuiltInWorldRayDirectionKHR;
1000 case glslang::EbvObjectRayOrigin:
1001 return spv::BuiltInObjectRayOriginKHR;
1002 case glslang::EbvObjectRayDirection:
1003 return spv::BuiltInObjectRayDirectionKHR;
1004 case glslang::EbvRayTmin:
1005 return spv::BuiltInRayTminKHR;
1006 case glslang::EbvRayTmax:
1007 return spv::BuiltInRayTmaxKHR;
1008 case glslang::EbvInstanceCustomIndex:
1009 return spv::BuiltInInstanceCustomIndexKHR;
1010 case glslang::EbvHitT:
Daniel Koche11a2c82020-11-30 11:57:34 -05001011 {
1012 // this is a GLSL alias of RayTmax
1013 // in SPV_NV_ray_tracing it has a dedicated builtin
1014 // but in SPV_KHR_ray_tracing it gets mapped to RayTmax
1015 auto& extensions = glslangIntermediate->getRequestedExtensions();
1016 if (extensions.find("GL_NV_ray_tracing") != extensions.end()) {
1017 return spv::BuiltInHitTNV;
1018 } else {
1019 return spv::BuiltInRayTmaxKHR;
1020 }
1021 }
Daniel Kochdb32b242020-03-17 20:42:47 -04001022 case glslang::EbvHitKind:
1023 return spv::BuiltInHitKindKHR;
1024 case glslang::EbvObjectToWorld:
1025 case glslang::EbvObjectToWorld3x4:
1026 return spv::BuiltInObjectToWorldKHR;
1027 case glslang::EbvWorldToObject:
1028 case glslang::EbvWorldToObject3x4:
1029 return spv::BuiltInWorldToObjectKHR;
1030 case glslang::EbvIncomingRayFlags:
1031 return spv::BuiltInIncomingRayFlagsKHR;
1032 case glslang::EbvGeometryIndex:
1033 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -04001034
1035 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -07001036 case glslang::EbvBaryCoordNV:
1037 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1038 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1039 return spv::BuiltInBaryCoordNV;
1040 case glslang::EbvBaryCoordNoPerspNV:
1041 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1042 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1043 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001044
1045 // mesh shaders
1046 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001047 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001048 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001049 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001050 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001051 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001052 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001053 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001054 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001055 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001056 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001057 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001058 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001059 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001060 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001061 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001062
1063 // sm builtins
1064 case glslang::EbvWarpsPerSM:
1065 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1066 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1067 return spv::BuiltInWarpsPerSMNV;
1068 case glslang::EbvSMCount:
1069 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1070 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1071 return spv::BuiltInSMCountNV;
1072 case glslang::EbvWarpID:
1073 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1074 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1075 return spv::BuiltInWarpIDNV;
1076 case glslang::EbvSMID:
1077 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1078 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1079 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001080#endif
1081
Rex Xu3e783f92017-02-22 16:44:48 +08001082 default:
1083 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001084 }
1085}
1086
Rex Xufc618912015-09-09 16:42:49 +08001087// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001088spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001089{
1090 assert(type.getBasicType() == glslang::EbtSampler);
1091
John Kessenichb9197c82019-08-11 07:41:45 -06001092#ifdef GLSLANG_WEB
1093 return spv::ImageFormatUnknown;
1094#endif
1095
John Kessenich5d0fa972016-02-15 11:57:00 -07001096 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001097 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001098 case glslang::ElfRg32f:
1099 case glslang::ElfRg16f:
1100 case glslang::ElfR11fG11fB10f:
1101 case glslang::ElfR16f:
1102 case glslang::ElfRgba16:
1103 case glslang::ElfRgb10A2:
1104 case glslang::ElfRg16:
1105 case glslang::ElfRg8:
1106 case glslang::ElfR16:
1107 case glslang::ElfR8:
1108 case glslang::ElfRgba16Snorm:
1109 case glslang::ElfRg16Snorm:
1110 case glslang::ElfRg8Snorm:
1111 case glslang::ElfR16Snorm:
1112 case glslang::ElfR8Snorm:
1113
1114 case glslang::ElfRg32i:
1115 case glslang::ElfRg16i:
1116 case glslang::ElfRg8i:
1117 case glslang::ElfR16i:
1118 case glslang::ElfR8i:
1119
1120 case glslang::ElfRgb10a2ui:
1121 case glslang::ElfRg32ui:
1122 case glslang::ElfRg16ui:
1123 case glslang::ElfRg8ui:
1124 case glslang::ElfR16ui:
1125 case glslang::ElfR8ui:
1126 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1127 break;
1128
Tobski8c1a3a02020-11-04 16:24:23 +00001129 case glslang::ElfR64ui:
1130 case glslang::ElfR64i:
1131 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
1132 builder.addCapability(spv::CapabilityInt64ImageEXT);
John Kessenich5d0fa972016-02-15 11:57:00 -07001133 default:
1134 break;
1135 }
1136
1137 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001138 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001139 case glslang::ElfNone: return spv::ImageFormatUnknown;
1140 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1141 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1142 case glslang::ElfR32f: return spv::ImageFormatR32f;
1143 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1144 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1145 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1146 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1147 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1148 case glslang::ElfR16f: return spv::ImageFormatR16f;
1149 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1150 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1151 case glslang::ElfRg16: return spv::ImageFormatRg16;
1152 case glslang::ElfRg8: return spv::ImageFormatRg8;
1153 case glslang::ElfR16: return spv::ImageFormatR16;
1154 case glslang::ElfR8: return spv::ImageFormatR8;
1155 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1156 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1157 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1158 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1159 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1160 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1161 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1162 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1163 case glslang::ElfR32i: return spv::ImageFormatR32i;
1164 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1165 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1166 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1167 case glslang::ElfR16i: return spv::ImageFormatR16i;
1168 case glslang::ElfR8i: return spv::ImageFormatR8i;
1169 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1170 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1171 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1172 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1173 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1174 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1175 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1176 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1177 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1178 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
Tobski8c1a3a02020-11-04 16:24:23 +00001179 case glslang::ElfR64ui: return spv::ImageFormatR64ui;
1180 case glslang::ElfR64i: return spv::ImageFormatR64i;
John Kessenich4016e382016-07-15 11:53:56 -06001181 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001182 }
1183}
1184
John Kessenich8985fc92020-03-03 10:25:07 -07001185spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1186 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001187{
John Kesseniche18fd202018-01-30 11:01:39 -07001188 if (selectionNode.getFlatten())
1189 return spv::SelectionControlFlattenMask;
1190 if (selectionNode.getDontFlatten())
1191 return spv::SelectionControlDontFlattenMask;
1192 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001193}
1194
John Kessenich8985fc92020-03-03 10:25:07 -07001195spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1196 const
steve-lunargf1709e72017-05-02 20:14:50 -06001197{
John Kesseniche18fd202018-01-30 11:01:39 -07001198 if (switchNode.getFlatten())
1199 return spv::SelectionControlFlattenMask;
1200 if (switchNode.getDontFlatten())
1201 return spv::SelectionControlDontFlattenMask;
1202 return spv::SelectionControlMaskNone;
1203}
1204
John Kessenicha2858d92018-01-31 08:11:18 -07001205// return a non-0 dependency if the dependency argument must be set
1206spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001207 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001208{
1209 spv::LoopControlMask control = spv::LoopControlMaskNone;
1210
1211 if (loopNode.getDontUnroll())
1212 control = control | spv::LoopControlDontUnrollMask;
1213 if (loopNode.getUnroll())
1214 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001215 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001216 control = control | spv::LoopControlDependencyInfiniteMask;
1217 else if (loopNode.getLoopDependency() > 0) {
1218 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001219 operands.push_back((unsigned int)loopNode.getLoopDependency());
1220 }
1221 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1222 if (loopNode.getMinIterations() > 0) {
1223 control = control | spv::LoopControlMinIterationsMask;
1224 operands.push_back(loopNode.getMinIterations());
1225 }
1226 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1227 control = control | spv::LoopControlMaxIterationsMask;
1228 operands.push_back(loopNode.getMaxIterations());
1229 }
1230 if (loopNode.getIterationMultiple() > 1) {
1231 control = control | spv::LoopControlIterationMultipleMask;
1232 operands.push_back(loopNode.getIterationMultiple());
1233 }
1234 if (loopNode.getPeelCount() > 0) {
1235 control = control | spv::LoopControlPeelCountMask;
1236 operands.push_back(loopNode.getPeelCount());
1237 }
1238 if (loopNode.getPartialCount() > 0) {
1239 control = control | spv::LoopControlPartialCountMask;
1240 operands.push_back(loopNode.getPartialCount());
1241 }
John Kessenicha2858d92018-01-31 08:11:18 -07001242 }
John Kesseniche18fd202018-01-30 11:01:39 -07001243
1244 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001245}
1246
John Kessenicha5c5fb62017-05-05 05:09:58 -06001247// Translate glslang type to SPIR-V storage class.
1248spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1249{
Torosdagli06c2eee2020-03-19 11:09:57 -04001250 if (type.getBasicType() == glslang::EbtRayQuery)
Daniel Kochffccefd2020-11-23 15:41:27 -05001251 return spv::StorageClassPrivate;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001252 if (type.getQualifier().isPipeInput())
1253 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001254 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001255 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001256
1257 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001258 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001259 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001260 return spv::StorageClassAtomicCounter;
1261 if (type.containsOpaque())
1262 return spv::StorageClassUniformConstant;
1263 }
1264
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001265 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001266 type.getQualifier().isShaderRecord()) {
1267 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001268 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001269
John Kessenichbed4e4f2017-09-08 02:38:07 -06001270 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001271 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001272 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001273 }
1274
1275 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001276 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001277 return spv::StorageClassPushConstant;
1278 if (type.getBasicType() == glslang::EbtBlock)
1279 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001280 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001281 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001282
Caio Marcelo de Oliveira Filho4bfbf622020-06-02 16:58:51 -07001283 if (type.getQualifier().storage == glslang::EvqShared && type.getBasicType() == glslang::EbtBlock) {
1284 builder.addExtension(spv::E_SPV_KHR_workgroup_memory_explicit_layout);
1285 builder.addCapability(spv::CapabilityWorkgroupMemoryExplicitLayoutKHR);
1286 return spv::StorageClassWorkgroup;
1287 }
1288
John Kessenichbed4e4f2017-09-08 02:38:07 -06001289 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001290 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1291 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1292 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001293 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001294#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001295 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1296 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1297 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1298 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1299 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001300#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001301 default:
1302 assert(0);
1303 break;
1304 }
1305
1306 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001307}
1308
John Kessenich5611c6d2018-04-05 11:25:02 -06001309// Add capabilities pertaining to how an array is indexed.
1310void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1311 const glslang::TType& indexType)
1312{
John Kessenichb9197c82019-08-11 07:41:45 -06001313#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001314 if (indexType.getQualifier().isNonUniform()) {
1315 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001316 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001317 if (baseType.getBasicType() == glslang::EbtSampler) {
1318 if (baseType.getQualifier().hasAttachment())
1319 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001320 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001321 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001322 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001323 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1324 else if (baseType.isImage())
1325 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1326 else if (baseType.isTexture())
1327 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1328 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1329 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1330 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1331 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1332 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1333 }
1334 } else {
1335 // assume a dynamically uniform index
1336 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001337 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001338 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001339 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001340 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001341 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001342 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001343 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001344 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001345 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001346 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001347 }
1348 }
John Kessenichb9197c82019-08-11 07:41:45 -06001349#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001350}
1351
qining25262b32016-05-06 17:25:16 -04001352// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001353// descriptor set.
1354bool IsDescriptorResource(const glslang::TType& type)
1355{
John Kessenichf7497e22016-03-08 21:36:22 -07001356 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001357 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001358 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001359 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001360 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001361
1362 // non block...
1363 // basically samplerXXX/subpass/sampler/texture are all included
1364 // if they are the global-scope-class, not the function parameter
1365 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001366 if (type.getBasicType() == glslang::EbtSampler ||
1367 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001368 return type.getQualifier().isUniformOrBuffer();
1369
1370 // None of the above.
1371 return false;
1372}
1373
John Kesseniche0b6cad2015-12-24 10:30:13 -07001374void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1375{
1376 if (child.layoutMatrix == glslang::ElmNone)
1377 child.layoutMatrix = parent.layoutMatrix;
1378
1379 if (parent.invariant)
1380 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001381 if (parent.flat)
1382 child.flat = true;
1383 if (parent.centroid)
1384 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001385#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001386 if (parent.nopersp)
1387 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001388 if (parent.explicitInterp)
1389 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001390 if (parent.perPrimitiveNV)
1391 child.perPrimitiveNV = true;
1392 if (parent.perViewNV)
1393 child.perViewNV = true;
1394 if (parent.perTaskNV)
1395 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001396 if (parent.patch)
1397 child.patch = true;
1398 if (parent.sample)
1399 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001400 if (parent.coherent)
1401 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001402 if (parent.devicecoherent)
1403 child.devicecoherent = true;
1404 if (parent.queuefamilycoherent)
1405 child.queuefamilycoherent = true;
1406 if (parent.workgroupcoherent)
1407 child.workgroupcoherent = true;
1408 if (parent.subgroupcoherent)
1409 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001410 if (parent.shadercallcoherent)
1411 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001412 if (parent.nonprivate)
1413 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001414 if (parent.volatil)
1415 child.volatil = true;
1416 if (parent.restrict)
1417 child.restrict = true;
1418 if (parent.readonly)
1419 child.readonly = true;
1420 if (parent.writeonly)
1421 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001422#endif
greg-lunarg639f5462020-11-12 11:10:07 -07001423 if (parent.nonUniform)
1424 child.nonUniform = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001425}
1426
John Kessenichf2b7f332016-09-01 17:05:23 -06001427bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001428{
John Kessenich7b9fa252016-01-21 18:56:57 -07001429 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001430 // - struct members might inherit from a struct declaration
1431 // (note that non-block structs don't explicitly inherit,
1432 // only implicitly, meaning no decoration involved)
1433 // - affect decorations on the struct members
1434 // (note smooth does not, and expecting something like volatile
1435 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001436 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001437 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001438}
1439
John Kessenich140f3df2015-06-26 16:58:36 -06001440//
1441// Implement the TGlslangToSpvTraverser class.
1442//
1443
John Kessenich8985fc92020-03-03 10:25:07 -07001444TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1445 const glslang::TIntermediate* glslangIntermediate,
1446 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1447 TIntermTraverser(true, false, true),
1448 options(options),
1449 shaderEntry(nullptr), currentFunction(nullptr),
1450 sequenceDepth(0), logger(buildLogger),
1451 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1452 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1453 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001454 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1455 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001456{
1457 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1458
1459 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001460 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1461 glslangIntermediate->getVersion());
1462
John Kessenich121853f2017-05-31 17:11:16 -06001463 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001464 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001465 builder.setSourceFile(glslangIntermediate->getSourceFile());
1466
1467 // Set the source shader's text. If for SPV version 1.0, include
1468 // a preamble in comments stating the OpModuleProcessed instructions.
1469 // Otherwise, emit those as actual instructions.
1470 std::string text;
1471 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1472 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001473 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001474 text.append("// OpModuleProcessed ");
1475 text.append(processes[p]);
1476 text.append("\n");
1477 } else
1478 builder.addModuleProcessed(processes[p]);
1479 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001480 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001481 text.append("#line 1\n");
1482 text.append(glslangIntermediate->getSourceText());
1483 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001484 // Pass name and text for all included files
1485 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1486 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1487 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001488 }
John Kessenich140f3df2015-06-26 16:58:36 -06001489 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001490
1491 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1492 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1493
1494 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1495 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
Jeremy Hayes13e27f92021-03-04 18:03:14 -07001496 builder.addIncorporatedExtension(spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001497 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001498 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001499 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001500 memoryModel = spv::MemoryModelVulkanKHR;
1501 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001502 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001503 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001504 builder.setMemoryModel(addressingModel, memoryModel);
1505
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001506 if (glslangIntermediate->usingVariablePointers()) {
1507 builder.addCapability(spv::CapabilityVariablePointers);
1508 }
1509
John Kessenicheee9d532016-09-19 18:09:30 -06001510 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1511 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001512
1513 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001514 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1515 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001516 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001517
1518 // Add the top-level modes for this shader.
1519
John Kessenich92187592016-02-01 13:45:25 -07001520 if (glslangIntermediate->getXfbMode()) {
1521 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001522 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001523 }
John Kessenich140f3df2015-06-26 16:58:36 -06001524
alelenv59216d52020-05-21 04:38:41 -07001525 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
Daniel Kochffccefd2020-11-23 15:41:27 -05001526 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingKHR);
alelenv75de1962020-04-08 21:09:20 -07001527 }
1528
John Kessenich140f3df2015-06-26 16:58:36 -06001529 unsigned int mode;
1530 switch (glslangIntermediate->getStage()) {
1531 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001532 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001533 break;
1534
John Kessenicha28f7a72019-08-06 07:00:58 -06001535 case EShLangFragment:
1536 builder.addCapability(spv::CapabilityShader);
1537 if (glslangIntermediate->getPixelCenterInteger())
1538 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1539
1540 if (glslangIntermediate->getOriginUpperLeft())
1541 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1542 else
1543 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1544
1545 if (glslangIntermediate->getEarlyFragmentTests())
1546 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1547
1548 if (glslangIntermediate->getPostDepthCoverage()) {
1549 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1550 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1551 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1552 }
1553
Greg Fischerb479ce02021-03-01 17:45:03 -07001554 if (glslangIntermediate->isDepthReplacing())
John Kessenichb9197c82019-08-11 07:41:45 -06001555 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1556
1557#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001558
John Kessenicha28f7a72019-08-06 07:00:58 -06001559 switch(glslangIntermediate->getDepth()) {
Greg Fischerb479ce02021-03-01 17:45:03 -07001560 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1561 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1562 case glslang::EldUnchanged: mode = spv::ExecutionModeDepthUnchanged; break;
1563 default: mode = spv::ExecutionModeMax; break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001564 }
1565 if (mode != spv::ExecutionModeMax)
1566 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001567 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001568 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1569 break;
1570 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1571 break;
1572 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1573 break;
1574 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1575 break;
1576 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1577 break;
1578 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1579 break;
1580 default: mode = spv::ExecutionModeMax;
1581 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001582 }
1583 if (mode != spv::ExecutionModeMax) {
1584 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1585 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1586 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1587 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1588 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1589 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1590 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1591 } else {
1592 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1593 }
1594 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1595 }
John Kessenichb9197c82019-08-11 07:41:45 -06001596#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001597 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001598
John Kessenicha28f7a72019-08-06 07:00:58 -06001599 case EShLangCompute:
1600 builder.addCapability(spv::CapabilityShader);
1601 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1602 glslangIntermediate->getLocalSize(1),
1603 glslangIntermediate->getLocalSize(2));
1604 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1605 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1606 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1607 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1608 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1609 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1610 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1611 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1612 }
1613 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001614#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001615 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001616 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001617 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001618
steve-lunarge7412492017-03-23 11:56:07 -06001619 glslang::TLayoutGeometry primitive;
1620
1621 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001622 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1623 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001624 primitive = glslangIntermediate->getOutputPrimitive();
1625 } else {
1626 primitive = glslangIntermediate->getInputPrimitive();
1627 }
1628
1629 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001630 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1631 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1632 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001633 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001634 }
John Kessenich4016e382016-07-15 11:53:56 -06001635 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001636 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1637
John Kesseniche6903322015-10-13 16:29:02 -06001638 switch (glslangIntermediate->getVertexSpacing()) {
1639 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1640 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1641 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001642 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001643 }
John Kessenich4016e382016-07-15 11:53:56 -06001644 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001645 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1646
1647 switch (glslangIntermediate->getVertexOrder()) {
1648 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1649 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001650 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001651 }
John Kessenich4016e382016-07-15 11:53:56 -06001652 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001653 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1654
1655 if (glslangIntermediate->getPointMode())
1656 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001657 break;
1658
1659 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001660 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001661 switch (glslangIntermediate->getInputPrimitive()) {
1662 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1663 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1664 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001665 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001666 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001667 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001668 }
John Kessenich4016e382016-07-15 11:53:56 -06001669 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001670 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001671
John Kessenich140f3df2015-06-26 16:58:36 -06001672 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1673
1674 switch (glslangIntermediate->getOutputPrimitive()) {
1675 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1676 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1677 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001678 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001679 }
John Kessenich4016e382016-07-15 11:53:56 -06001680 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001681 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1682 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1683 break;
1684
Daniel Kochdb32b242020-03-17 20:42:47 -04001685 case EShLangRayGen:
1686 case EShLangIntersect:
1687 case EShLangAnyHit:
1688 case EShLangClosestHit:
1689 case EShLangMiss:
1690 case EShLangCallable:
1691 {
1692 auto& extensions = glslangIntermediate->getRequestedExtensions();
1693 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
Daniel Kochffccefd2020-11-23 15:41:27 -05001694 builder.addCapability(spv::CapabilityRayTracingKHR);
Daniel Kochdb32b242020-03-17 20:42:47 -04001695 builder.addExtension("SPV_KHR_ray_tracing");
1696 }
1697 else {
1698 builder.addCapability(spv::CapabilityRayTracingNV);
1699 builder.addExtension("SPV_NV_ray_tracing");
1700 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001701 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001702 }
Chao Chen3c366992018-09-19 11:41:59 -07001703 case EShLangTaskNV:
1704 case EShLangMeshNV:
1705 builder.addCapability(spv::CapabilityMeshShadingNV);
1706 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1707 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1708 glslangIntermediate->getLocalSize(1),
1709 glslangIntermediate->getLocalSize(2));
1710 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001711 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1712 glslangIntermediate->getVertices());
1713 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1714 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001715
1716 switch (glslangIntermediate->getOutputPrimitive()) {
1717 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1718 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1719 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1720 default: mode = spv::ExecutionModeMax; break;
1721 }
1722 if (mode != spv::ExecutionModeMax)
1723 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1724 }
1725 break;
1726#endif
1727
John Kessenich140f3df2015-06-26 16:58:36 -06001728 default:
1729 break;
1730 }
John Kessenich140f3df2015-06-26 16:58:36 -06001731}
1732
John Kessenichfca82622016-11-26 13:23:20 -07001733// Finish creating SPV, after the traversal is complete.
1734void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001735{
John Kessenichf04c51b2018-08-03 15:56:12 -06001736 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001737 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001738 builder.setBuildPoint(shaderEntry->getLastBlock());
1739 builder.leaveFunction();
1740 }
1741
John Kessenich7ba63412015-12-20 17:37:07 -07001742 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001743 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1744 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001745
David Neto8c3d5b42019-10-21 14:50:31 -04001746 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001747 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001748 // Note: WebGPU code generation must have the opportunity to aggressively
1749 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001750 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001751}
1752
John Kessenichfca82622016-11-26 13:23:20 -07001753// Write the SPV into 'out'.
1754void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001755{
John Kessenichfca82622016-11-26 13:23:20 -07001756 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001757}
1758
1759//
1760// Implement the traversal functions.
1761//
1762// Return true from interior nodes to have the external traversal
1763// continue on to children. Return false if children were
1764// already processed.
1765//
1766
1767//
qining25262b32016-05-06 17:25:16 -04001768// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001769// - uniform/input reads
1770// - output writes
1771// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1772// - something simple that degenerates into the last bullet
1773//
1774void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1775{
qining75d1d802016-04-06 14:42:01 -04001776 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001777 if (symbol->getType().isStruct())
1778 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1779
qining75d1d802016-04-06 14:42:01 -04001780 if (symbol->getType().getQualifier().isSpecConstant())
1781 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1782
Rex Xuf6e0fe82020-10-23 22:54:35 +08001783#ifdef ENABLE_HLSL
1784 // Skip symbol handling if it is string-typed
1785 if (symbol->getBasicType() == glslang::EbtString)
1786 return;
1787#endif
1788
John Kessenich140f3df2015-06-26 16:58:36 -06001789 // getSymbolId() will set up all the IO decorations on the first call.
1790 // Formal function parameters were mapped during makeFunctions().
1791 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001792
John Kessenich7ba63412015-12-20 17:37:07 -07001793 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001794 if (!symbol->getType().getQualifier().isParamInput() &&
1795 !symbol->getType().getQualifier().isParamOutput()) {
1796 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1797 // Consider adding to the OpEntryPoint interface list.
1798 // Only looking at structures if they have at least one member.
1799 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1800 spv::StorageClass sc = builder.getStorageClass(id);
1801 // Before SPIR-V 1.4, we only want to include Input and Output.
1802 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001803 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001804 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1805 iOSet.insert(id);
1806 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001807 }
John Kessenich5f77d862017-09-19 11:09:59 -06001808 }
John Kessenich9c14f772019-06-17 08:38:35 -06001809
Daniel Kochdb32b242020-03-17 20:42:47 -04001810 // If the SPIR-V type is required to be different than the AST type
1811 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001812 // translate now from the SPIR-V type to the AST type, for the consuming
1813 // operation.
1814 // Note this turns it from an l-value to an r-value.
1815 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1816 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1817 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001818 }
1819
1820 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001821 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001822 // Prepare to generate code for the access
1823
1824 // L-value chains will be computed left to right. We're on the symbol now,
1825 // which is the left-most part of the access chain, so now is "clear" time,
1826 // followed by setting the base.
1827 builder.clearAccessChain();
1828
1829 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001830 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001831 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001832 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001833 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001834 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001835 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001836 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001837 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1838 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001839 builder.setAccessChainRValue(id);
1840 else
1841 builder.setAccessChainLValue(id);
1842 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001843
John Kessenichb9197c82019-08-11 07:41:45 -06001844#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001845 // Process linkage-only nodes for any special additional interface work.
1846 if (linkageOnly) {
1847 if (glslangIntermediate->getHlslFunctionality1()) {
1848 // Map implicit counter buffers to their originating buffers, which should have been
1849 // seen by now, given earlier pruning of unused counters, and preservation of order
1850 // of declaration.
1851 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1852 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1853 // Save possible originating buffers for counter buffers, keyed by
1854 // making the potential counter-buffer name.
1855 std::string keyName = symbol->getName().c_str();
1856 keyName = glslangIntermediate->addCounterBufferName(keyName);
1857 counterOriginator[keyName] = symbol;
1858 } else {
1859 // Handle a counter buffer, by finding the saved originating buffer.
1860 std::string keyName = symbol->getName().c_str();
1861 auto it = counterOriginator.find(keyName);
1862 if (it != counterOriginator.end()) {
1863 id = getSymbolId(it->second);
1864 if (id != spv::NoResult) {
1865 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001866 if (counterId != spv::NoResult) {
1867 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001868 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001869 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001870 }
1871 }
1872 }
1873 }
1874 }
1875 }
John Kessenich155d3512019-08-08 23:29:20 -06001876#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001877}
1878
1879bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1880{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001881 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001882 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1883 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1884 }
1885 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1886 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1887 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001888
qining40887662016-04-03 22:20:42 -04001889 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1890 if (node->getType().getQualifier().isSpecConstant())
1891 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1892
John Kessenich140f3df2015-06-26 16:58:36 -06001893 // First, handle special cases
1894 switch (node->getOp()) {
1895 case glslang::EOpAssign:
1896 case glslang::EOpAddAssign:
1897 case glslang::EOpSubAssign:
1898 case glslang::EOpMulAssign:
1899 case glslang::EOpVectorTimesMatrixAssign:
1900 case glslang::EOpVectorTimesScalarAssign:
1901 case glslang::EOpMatrixTimesScalarAssign:
1902 case glslang::EOpMatrixTimesMatrixAssign:
1903 case glslang::EOpDivAssign:
1904 case glslang::EOpModAssign:
1905 case glslang::EOpAndAssign:
1906 case glslang::EOpInclusiveOrAssign:
1907 case glslang::EOpExclusiveOrAssign:
1908 case glslang::EOpLeftShiftAssign:
1909 case glslang::EOpRightShiftAssign:
1910 // A bin-op assign "a += b" means the same thing as "a = a + b"
1911 // where a is evaluated before b. For a simple assignment, GLSL
1912 // says to evaluate the left before the right. So, always, left
1913 // node then right node.
1914 {
1915 // get the left l-value, save it away
1916 builder.clearAccessChain();
1917 node->getLeft()->traverse(this);
1918 spv::Builder::AccessChain lValue = builder.getAccessChain();
1919
1920 // evaluate the right
1921 builder.clearAccessChain();
1922 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001923 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001924
1925 if (node->getOp() != glslang::EOpAssign) {
1926 // the left is also an r-value
1927 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001928 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001929
1930 // do the operation
greg-lunarg639f5462020-11-12 11:10:07 -07001931 spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
1932 coherentFlags |= TranslateCoherent(node->getRight()->getType());
John Kessenichead86222018-03-28 18:01:20 -06001933 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001934 TranslateNoContractionDecoration(node->getType().getQualifier()),
greg-lunarg639f5462020-11-12 11:10:07 -07001935 TranslateNonUniformDecoration(coherentFlags) };
John Kessenichead86222018-03-28 18:01:20 -06001936 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001937 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1938 node->getType().getBasicType());
1939
1940 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001941 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001942 }
1943
1944 // store the result
1945 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001946 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001947
1948 // assignments are expressions having an rValue after they are evaluated...
1949 builder.clearAccessChain();
1950 builder.setAccessChainRValue(rValue);
1951 }
1952 return false;
1953 case glslang::EOpIndexDirect:
1954 case glslang::EOpIndexDirectStruct:
1955 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001956 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001957 // Get the left part of the access chain.
1958 node->getLeft()->traverse(this);
1959
1960 // Add the next element in the chain
1961
David Netoa901ffe2016-06-08 14:11:40 +01001962 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001963 if (! node->getLeft()->getType().isArray() &&
1964 node->getLeft()->getType().isVector() &&
1965 node->getOp() == glslang::EOpIndexDirect) {
greg-lunarg639f5462020-11-12 11:10:07 -07001966 // Swizzle is uniform so propagate uniform into access chain
1967 spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
1968 coherentFlags.nonUniform = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06001969 // This is essentially a hard-coded vector swizzle of size 1,
1970 // so short circuit the access-chain stuff with a swizzle.
1971 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001972 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001973 int dummySize;
1974 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
greg-lunarg639f5462020-11-12 11:10:07 -07001975 coherentFlags,
John Kessenich8985fc92020-03-03 10:25:07 -07001976 glslangIntermediate->getBaseAlignmentScalar(
1977 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001978 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001979
1980 // Load through a block reference is performed with a dot operator that
1981 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1982 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001983 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001984 !node->getLeft()->getType().isArray() &&
1985 node->getOp() == glslang::EOpIndexDirectStruct)
1986 {
1987 spv::Id left = accessChainLoad(node->getLeft()->getType());
1988 builder.clearAccessChain();
1989 builder.setAccessChainLValue(left);
1990 }
1991
David Netoa901ffe2016-06-08 14:11:40 +01001992 int spvIndex = glslangIndex;
1993 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1994 node->getOp() == glslang::EOpIndexDirectStruct)
1995 {
1996 // This may be, e.g., an anonymous block-member selection, which generally need
1997 // index remapping due to hidden members in anonymous blocks.
Chow93b400f2020-11-12 15:54:16 +08001998 long long glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
Roy05a5b532020-01-03 16:21:34 +08001999 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
2000 std::vector<int>& remapper = memberRemapper[glslangId];
2001 assert(remapper.size() > 0);
2002 spvIndex = remapper[glslangIndex];
2003 }
David Netoa901ffe2016-06-08 14:11:40 +01002004 }
John Kessenichebb50532016-05-16 19:22:05 -06002005
greg-lunarg639f5462020-11-12 11:10:07 -07002006 // Struct reference propagates uniform lvalue
2007 spv::Builder::AccessChain::CoherentFlags coherentFlags =
2008 TranslateCoherent(node->getLeft()->getType());
2009 coherentFlags.nonUniform = 0;
2010
David Netoa901ffe2016-06-08 14:11:40 +01002011 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07002012 builder.accessChainPush(builder.makeIntConstant(spvIndex),
greg-lunarg639f5462020-11-12 11:10:07 -07002013 coherentFlags,
John Kessenich8985fc92020-03-03 10:25:07 -07002014 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01002015
2016 // Add capabilities here for accessing PointSize and clip/cull distance.
2017 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06002018 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01002019 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06002020 }
2021 }
2022 return false;
2023 case glslang::EOpIndexIndirect:
2024 {
John Kessenich61a5ce12019-02-07 08:04:12 -07002025 // Array, matrix, or vector indirection with variable index.
2026 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06002027 // matrices are arrays of vectors, so will also work for a matrix.
2028 // Will use the access chain's 'component' for variable index into a vector.
2029
2030 // This adapter is building access chains left to right.
2031 // Set up the access chain to the left.
2032 node->getLeft()->traverse(this);
2033
2034 // save it so that computing the right side doesn't trash it
2035 spv::Builder::AccessChain partial = builder.getAccessChain();
2036
2037 // compute the next index in the chain
2038 builder.clearAccessChain();
2039 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002040 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002041
John Kessenich5611c6d2018-04-05 11:25:02 -06002042 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
2043
John Kessenich140f3df2015-06-26 16:58:36 -06002044 // restore the saved access chain
2045 builder.setAccessChain(partial);
2046
greg-lunarg639f5462020-11-12 11:10:07 -07002047 // Only if index is nonUniform should we propagate nonUniform into access chain
2048 spv::Builder::AccessChain::CoherentFlags index_flags = TranslateCoherent(node->getRight()->getType());
2049 spv::Builder::AccessChain::CoherentFlags coherent_flags = TranslateCoherent(node->getLeft()->getType());
2050 coherent_flags.nonUniform = index_flags.nonUniform;
2051
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002052 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
2053 int dummySize;
greg-lunarg639f5462020-11-12 11:10:07 -07002054 builder.accessChainPushComponent(
2055 index, convertGlslangToSpvType(node->getLeft()->getType()), coherent_flags,
John Kessenich8985fc92020-03-03 10:25:07 -07002056 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2057 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002058 } else
greg-lunarg639f5462020-11-12 11:10:07 -07002059 builder.accessChainPush(index, coherent_flags,
2060 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06002061 }
2062 return false;
2063 case glslang::EOpVectorSwizzle:
2064 {
2065 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002066 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06002067 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002068 int dummySize;
2069 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
2070 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07002071 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2072 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06002073 }
2074 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07002075 case glslang::EOpMatrixSwizzle:
2076 logger->missingFunctionality("matrix swizzle");
2077 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06002078 case glslang::EOpLogicalOr:
2079 case glslang::EOpLogicalAnd:
2080 {
2081
2082 // These may require short circuiting, but can sometimes be done as straight
2083 // binary operations. The right operand must be short circuited if it has
2084 // side effects, and should probably be if it is complex.
2085 if (isTrivial(node->getRight()->getAsTyped()))
2086 break; // handle below as a normal binary operation
2087 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07002088 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
2089 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06002090 builder.clearAccessChain();
2091 builder.setAccessChainRValue(result);
2092 }
2093 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002094 default:
2095 break;
2096 }
2097
2098 // Assume generic binary op...
2099
John Kessenich32cfd492016-02-02 12:37:46 -07002100 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002101 builder.clearAccessChain();
2102 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002103 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002104
John Kessenich32cfd492016-02-02 12:37:46 -07002105 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002106 builder.clearAccessChain();
2107 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002108 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002109
John Kessenich32cfd492016-02-02 12:37:46 -07002110 // get result
John Kessenichead86222018-03-28 18:01:20 -06002111 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002112 TranslateNoContractionDecoration(node->getType().getQualifier()),
2113 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002114 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002115 convertGlslangToSpvType(node->getType()), left, right,
2116 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002117
John Kessenich50e57562015-12-21 21:21:11 -07002118 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002119 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002120 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002121 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002122 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002123 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002124 return false;
2125 }
John Kessenich140f3df2015-06-26 16:58:36 -06002126}
2127
John Kessenich9c14f772019-06-17 08:38:35 -06002128// Figure out what, if any, type changes are needed when accessing a specific built-in.
2129// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2130// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002131std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002132 const glslang::TType& glslangType)
2133{
Daniel Kochdb32b242020-03-17 20:42:47 -04002134 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002135 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002136 case glslang::EbvSubGroupEqMask:
2137 case glslang::EbvSubGroupGeMask:
2138 case glslang::EbvSubGroupGtMask:
2139 case glslang::EbvSubGroupLeMask:
2140 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002141 // these require changing a 64-bit scaler -> a vector of 32-bit components
2142 if (glslangType.isVector())
2143 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05002144 spv::Id ivec4_type = builder.makeVectorType(builder.makeUintType(32), 4);
2145 spv::Id uint64_type = builder.makeUintType(64);
2146 std::pair<spv::Id, spv::Id> ret(ivec4_type, uint64_type);
John Kessenich9c14f772019-06-17 08:38:35 -06002147 return ret;
2148 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002149 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2150 // builtins. During visitBinary we insert a transpose
2151 case glslang::EbvWorldToObject3x4:
2152 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002153 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2154 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2155 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002156 return ret;
2157 }
John Kessenich9c14f772019-06-17 08:38:35 -06002158 default:
2159 break;
2160 }
2161
2162 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2163 return ret;
2164}
2165
2166// For an object previously identified (see getForcedType() and forceType)
2167// as needing type translations, do the translation needed for a load, turning
2168// an L-value into in R-value.
2169spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2170{
2171 const auto forceIt = forceType.find(object);
2172 if (forceIt == forceType.end())
2173 return object;
2174
2175 spv::Id desiredTypeId = forceIt->second;
2176 spv::Id objectTypeId = builder.getTypeId(object);
2177 assert(builder.isPointerType(objectTypeId));
2178 objectTypeId = builder.getContainedTypeId(objectTypeId);
2179 if (builder.isVectorType(objectTypeId) &&
2180 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2181 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2182 // handle 32-bit v.xy* -> 64-bit
2183 builder.clearAccessChain();
2184 builder.setAccessChainLValue(object);
greg-lunarg639f5462020-11-12 11:10:07 -07002185 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
John Kessenich9c14f772019-06-17 08:38:35 -06002186 std::vector<spv::Id> components;
2187 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2188 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2189
2190 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2191 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2192 builder.createCompositeConstruct(vecType, components));
2193 } else {
2194 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2195 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002196 } else if (builder.isMatrixType(objectTypeId)) {
2197 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2198 // and we insert a transpose after loading the original non-transposed builtins
2199 builder.clearAccessChain();
2200 builder.setAccessChainLValue(object);
greg-lunarg639f5462020-11-12 11:10:07 -07002201 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
Daniel Kochdb32b242020-03-17 20:42:47 -04002202 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2203
2204 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002205 logger->missingFunctionality("forcing non 32-bit vector type");
2206 }
2207
2208 return object;
2209}
2210
John Kessenich140f3df2015-06-26 16:58:36 -06002211bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2212{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002213 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002214
qining40887662016-04-03 22:20:42 -04002215 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2216 if (node->getType().getQualifier().isSpecConstant())
2217 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2218
John Kessenichfc51d282015-08-19 13:34:18 -06002219 spv::Id result = spv::NoResult;
2220
2221 // try texturing first
2222 result = createImageTextureFunctionCall(node);
2223 if (result != spv::NoResult) {
2224 builder.clearAccessChain();
2225 builder.setAccessChainRValue(result);
2226
2227 return false; // done with this node
2228 }
2229
2230 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002231
2232 if (node->getOp() == glslang::EOpArrayLength) {
2233 // Quite special; won't want to evaluate the operand.
2234
John Kessenich5611c6d2018-04-05 11:25:02 -06002235 // Currently, the front-end does not allow .length() on an array until it is sized,
2236 // except for the last block membeor of an SSBO.
2237 // TODO: If this changes, link-time sized arrays might show up here, and need their
2238 // size extracted.
2239
John Kessenichc9a80832015-09-12 12:17:44 -06002240 // Normal .length() would have been constant folded by the front-end.
2241 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002242 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002243
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002244 spv::Id length;
2245 if (node->getOperand()->getType().isCoopMat()) {
2246 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2247
2248 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2249 assert(builder.isCooperativeMatrixType(typeId));
2250
2251 length = builder.createCooperativeMatrixLength(typeId);
2252 } else {
2253 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2254 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002255 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2256 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002257 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2258 }
John Kessenichc9a80832015-09-12 12:17:44 -06002259
John Kessenich8c869672018-11-28 07:01:37 -07002260 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2261 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2262 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002263 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2264 if (builder.isInSpecConstCodeGenMode()) {
2265 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2266 } else {
2267 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2268 }
2269 }
John Kessenich8c869672018-11-28 07:01:37 -07002270
John Kessenichc9a80832015-09-12 12:17:44 -06002271 builder.clearAccessChain();
2272 builder.setAccessChainRValue(length);
2273
2274 return false;
2275 }
2276
John Kessenichfc51d282015-08-19 13:34:18 -06002277 // Start by evaluating the operand
2278
John Kessenich8c8505c2016-07-26 12:50:38 -06002279 // Does it need a swizzle inversion? If so, evaluation is inverted;
2280 // operate first on the swizzle base, then apply the swizzle.
2281 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002282 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2283 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002284 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2285 invertedType = getInvertedSwizzleType(*node->getOperand());
2286
John Kessenich140f3df2015-06-26 16:58:36 -06002287 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002288 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002289 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002290 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002291 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002292 operandNode = node->getOperand();
2293
2294 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002295
Rex Xufc618912015-09-09 16:42:49 +08002296 spv::Id operand = spv::NoResult;
2297
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002298 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2299
John Kessenichfb4f2332019-08-09 03:49:15 -06002300#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002301 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2302 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002303 node->getOp() == glslang::EOpAtomicCounter ||
Greg Fischer7fbaca02021-03-31 15:24:48 -06002304 (node->getOp() == glslang::EOpInterpolateAtCentroid &&
2305 glslangIntermediate->getSource() != glslang::EShSourceHlsl) ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002306 node->getOp() == glslang::EOpRayQueryProceed ||
2307 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2308 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2309 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2310 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2311 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2312 node->getOp() == glslang::EOpRayQueryTerminate ||
2313 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002314 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002315 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2316 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2317 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002318#endif
2319 {
John Kessenich32cfd492016-02-02 12:37:46 -07002320 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002321 }
John Kessenich140f3df2015-06-26 16:58:36 -06002322
John Kessenichead86222018-03-28 18:01:20 -06002323 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002324 TranslateNoContractionDecoration(node->getType().getQualifier()),
2325 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002326
2327 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002328 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002329 result = createConversion(node->getOp(), decorations, resultType(), operand,
2330 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002331
2332 // if not, then possibly an operation
2333 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002334 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2335 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002336
2337 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002338 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002339 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002340 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002341 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002342
John Kessenich140f3df2015-06-26 16:58:36 -06002343 builder.clearAccessChain();
2344 builder.setAccessChainRValue(result);
2345
2346 return false; // done with this node
2347 }
2348
2349 // it must be a special case, check...
2350 switch (node->getOp()) {
2351 case glslang::EOpPostIncrement:
2352 case glslang::EOpPostDecrement:
2353 case glslang::EOpPreIncrement:
2354 case glslang::EOpPreDecrement:
2355 {
2356 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002357 spv::Id one = 0;
2358 if (node->getBasicType() == glslang::EbtFloat)
2359 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002360#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002361 else if (node->getBasicType() == glslang::EbtDouble)
2362 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002363 else if (node->getBasicType() == glslang::EbtFloat16)
2364 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002365 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2366 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002367 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2368 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002369 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2370 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002371#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002372 else
2373 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002374 glslang::TOperator op;
2375 if (node->getOp() == glslang::EOpPreIncrement ||
2376 node->getOp() == glslang::EOpPostIncrement)
2377 op = glslang::EOpAdd;
2378 else
2379 op = glslang::EOpSub;
2380
John Kessenichead86222018-03-28 18:01:20 -06002381 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002382 convertGlslangToSpvType(node->getType()), operand, one,
2383 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002384 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002385
2386 // The result of operation is always stored, but conditionally the
2387 // consumed result. The consumed result is always an r-value.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002388 builder.accessChainStore(result,
greg-lunarg639f5462020-11-12 11:10:07 -07002389 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags));
John Kessenich140f3df2015-06-26 16:58:36 -06002390 builder.clearAccessChain();
2391 if (node->getOp() == glslang::EOpPreIncrement ||
2392 node->getOp() == glslang::EOpPreDecrement)
2393 builder.setAccessChainRValue(result);
2394 else
2395 builder.setAccessChainRValue(operand);
2396 }
2397
2398 return false;
2399
John Kessenich155d3512019-08-08 23:29:20 -06002400#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002401 case glslang::EOpEmitStreamVertex:
2402 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2403 return false;
2404 case glslang::EOpEndStreamPrimitive:
2405 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2406 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002407 case glslang::EOpRayQueryTerminate:
2408 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2409 return false;
2410 case glslang::EOpRayQueryConfirmIntersection:
2411 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2412 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002413#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002414
2415 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002416 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002417 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002418 }
John Kessenich140f3df2015-06-26 16:58:36 -06002419}
2420
Jeff Bolz53134492019-06-25 13:31:10 -05002421// Construct a composite object, recursively copying members if their types don't match
2422spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2423{
2424 for (int c = 0; c < (int)constituents.size(); ++c) {
2425 spv::Id& constituent = constituents[c];
2426 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2427 spv::Id rType = builder.getTypeId(constituent);
2428 if (lType != rType) {
2429 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2430 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2431 } else if (builder.isStructType(rType)) {
2432 std::vector<spv::Id> rTypeConstituents;
2433 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2434 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002435 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2436 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002437 }
2438 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2439 } else {
2440 assert(builder.isArrayType(rType));
2441 std::vector<spv::Id> rTypeConstituents;
2442 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2443
2444 spv::Id elementRType = builder.getContainedTypeId(rType);
2445 for (int i = 0; i < numrTypeConstituents; ++i) {
2446 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2447 }
2448 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2449 }
2450 }
2451 }
2452 return builder.createCompositeConstruct(resultTypeId, constituents);
2453}
2454
John Kessenich140f3df2015-06-26 16:58:36 -06002455bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2456{
qining27e04a02016-04-14 16:40:20 -04002457 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2458 if (node->getType().getQualifier().isSpecConstant())
2459 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2460
John Kessenichfc51d282015-08-19 13:34:18 -06002461 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002462 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2463 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2464 // SPIR-V, for an out parameter
2465 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002466
John Kessenich8985fc92020-03-03 10:25:07 -07002467 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2468 invertedType :
2469 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002470
2471 // try texturing
2472 result = createImageTextureFunctionCall(node);
2473 if (result != spv::NoResult) {
2474 builder.clearAccessChain();
2475 builder.setAccessChainRValue(result);
2476
2477 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002478 }
2479#ifndef GLSLANG_WEB
2480 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002481 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002482 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002483 // "imageStore" is a special case, which has no result
2484 return false;
2485 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002486#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002487
John Kessenich140f3df2015-06-26 16:58:36 -06002488 glslang::TOperator binOp = glslang::EOpNull;
2489 bool reduceComparison = true;
2490 bool isMatrix = false;
2491 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002492 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002493
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002494 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2495
John Kessenich140f3df2015-06-26 16:58:36 -06002496 assert(node->getOp());
2497
John Kessenichf6640762016-08-01 19:44:00 -06002498 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002499
2500 switch (node->getOp()) {
2501 case glslang::EOpSequence:
2502 {
2503 if (preVisit)
2504 ++sequenceDepth;
2505 else
2506 --sequenceDepth;
2507
2508 if (sequenceDepth == 1) {
2509 // If this is the parent node of all the functions, we want to see them
2510 // early, so all call points have actual SPIR-V functions to reference.
2511 // In all cases, still let the traverser visit the children for us.
2512 makeFunctions(node->getAsAggregate()->getSequence());
2513
John Kessenich6fccb3c2016-09-19 16:01:41 -06002514 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002515 // anything else gets there, so visit out of order, doing them all now.
2516 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2517
Daniel Kochffccefd2020-11-23 15:41:27 -05002518 //Pre process linker objects for ray tracing stages
2519 if (glslangIntermediate->isRayTracingStage())
2520 collectRayTracingLinkerObjects();
2521
John Kessenich6a60c2f2016-12-08 21:01:59 -07002522 // 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 -06002523 // so do them manually.
2524 visitFunctions(node->getAsAggregate()->getSequence());
2525
2526 return false;
2527 }
2528
2529 return true;
2530 }
2531 case glslang::EOpLinkerObjects:
2532 {
2533 if (visit == glslang::EvPreVisit)
2534 linkageOnly = true;
2535 else
2536 linkageOnly = false;
2537
2538 return true;
2539 }
2540 case glslang::EOpComma:
2541 {
2542 // processing from left to right naturally leaves the right-most
2543 // lying around in the access chain
2544 glslang::TIntermSequence& glslangOperands = node->getSequence();
2545 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2546 glslangOperands[i]->traverse(this);
2547
2548 return false;
2549 }
2550 case glslang::EOpFunction:
2551 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002552 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002553 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002554 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002555 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002556 } else {
2557 handleFunctionEntry(node);
2558 }
2559 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002560 if (inEntryPoint)
2561 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002562 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002563 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002564 }
2565
2566 return true;
2567 case glslang::EOpParameters:
2568 // Parameters will have been consumed by EOpFunction processing, but not
2569 // the body, so we still visited the function node's children, making this
2570 // child redundant.
2571 return false;
2572 case glslang::EOpFunctionCall:
2573 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002574 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002575 if (node->isUserDefined())
2576 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002577 if (result) {
2578 builder.clearAccessChain();
2579 builder.setAccessChainRValue(result);
2580 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002581 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002582
2583 return false;
2584 }
2585 case glslang::EOpConstructMat2x2:
2586 case glslang::EOpConstructMat2x3:
2587 case glslang::EOpConstructMat2x4:
2588 case glslang::EOpConstructMat3x2:
2589 case glslang::EOpConstructMat3x3:
2590 case glslang::EOpConstructMat3x4:
2591 case glslang::EOpConstructMat4x2:
2592 case glslang::EOpConstructMat4x3:
2593 case glslang::EOpConstructMat4x4:
2594 case glslang::EOpConstructDMat2x2:
2595 case glslang::EOpConstructDMat2x3:
2596 case glslang::EOpConstructDMat2x4:
2597 case glslang::EOpConstructDMat3x2:
2598 case glslang::EOpConstructDMat3x3:
2599 case glslang::EOpConstructDMat3x4:
2600 case glslang::EOpConstructDMat4x2:
2601 case glslang::EOpConstructDMat4x3:
2602 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002603 case glslang::EOpConstructIMat2x2:
2604 case glslang::EOpConstructIMat2x3:
2605 case glslang::EOpConstructIMat2x4:
2606 case glslang::EOpConstructIMat3x2:
2607 case glslang::EOpConstructIMat3x3:
2608 case glslang::EOpConstructIMat3x4:
2609 case glslang::EOpConstructIMat4x2:
2610 case glslang::EOpConstructIMat4x3:
2611 case glslang::EOpConstructIMat4x4:
2612 case glslang::EOpConstructUMat2x2:
2613 case glslang::EOpConstructUMat2x3:
2614 case glslang::EOpConstructUMat2x4:
2615 case glslang::EOpConstructUMat3x2:
2616 case glslang::EOpConstructUMat3x3:
2617 case glslang::EOpConstructUMat3x4:
2618 case glslang::EOpConstructUMat4x2:
2619 case glslang::EOpConstructUMat4x3:
2620 case glslang::EOpConstructUMat4x4:
2621 case glslang::EOpConstructBMat2x2:
2622 case glslang::EOpConstructBMat2x3:
2623 case glslang::EOpConstructBMat2x4:
2624 case glslang::EOpConstructBMat3x2:
2625 case glslang::EOpConstructBMat3x3:
2626 case glslang::EOpConstructBMat3x4:
2627 case glslang::EOpConstructBMat4x2:
2628 case glslang::EOpConstructBMat4x3:
2629 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002630 case glslang::EOpConstructF16Mat2x2:
2631 case glslang::EOpConstructF16Mat2x3:
2632 case glslang::EOpConstructF16Mat2x4:
2633 case glslang::EOpConstructF16Mat3x2:
2634 case glslang::EOpConstructF16Mat3x3:
2635 case glslang::EOpConstructF16Mat3x4:
2636 case glslang::EOpConstructF16Mat4x2:
2637 case glslang::EOpConstructF16Mat4x3:
2638 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002639 isMatrix = true;
2640 // fall through
2641 case glslang::EOpConstructFloat:
2642 case glslang::EOpConstructVec2:
2643 case glslang::EOpConstructVec3:
2644 case glslang::EOpConstructVec4:
2645 case glslang::EOpConstructDouble:
2646 case glslang::EOpConstructDVec2:
2647 case glslang::EOpConstructDVec3:
2648 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002649 case glslang::EOpConstructFloat16:
2650 case glslang::EOpConstructF16Vec2:
2651 case glslang::EOpConstructF16Vec3:
2652 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002653 case glslang::EOpConstructBool:
2654 case glslang::EOpConstructBVec2:
2655 case glslang::EOpConstructBVec3:
2656 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002657 case glslang::EOpConstructInt8:
2658 case glslang::EOpConstructI8Vec2:
2659 case glslang::EOpConstructI8Vec3:
2660 case glslang::EOpConstructI8Vec4:
2661 case glslang::EOpConstructUint8:
2662 case glslang::EOpConstructU8Vec2:
2663 case glslang::EOpConstructU8Vec3:
2664 case glslang::EOpConstructU8Vec4:
2665 case glslang::EOpConstructInt16:
2666 case glslang::EOpConstructI16Vec2:
2667 case glslang::EOpConstructI16Vec3:
2668 case glslang::EOpConstructI16Vec4:
2669 case glslang::EOpConstructUint16:
2670 case glslang::EOpConstructU16Vec2:
2671 case glslang::EOpConstructU16Vec3:
2672 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002673 case glslang::EOpConstructInt:
2674 case glslang::EOpConstructIVec2:
2675 case glslang::EOpConstructIVec3:
2676 case glslang::EOpConstructIVec4:
2677 case glslang::EOpConstructUint:
2678 case glslang::EOpConstructUVec2:
2679 case glslang::EOpConstructUVec3:
2680 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002681 case glslang::EOpConstructInt64:
2682 case glslang::EOpConstructI64Vec2:
2683 case glslang::EOpConstructI64Vec3:
2684 case glslang::EOpConstructI64Vec4:
2685 case glslang::EOpConstructUint64:
2686 case glslang::EOpConstructU64Vec2:
2687 case glslang::EOpConstructU64Vec3:
2688 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002689 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002690 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002691 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002692 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002693 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002694 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002695 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002696 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002697 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002698 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002699 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002700 else if (node->getOp() == glslang::EOpConstructStruct ||
2701 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2702 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002703 std::vector<spv::Id> constituents;
2704 for (int c = 0; c < (int)arguments.size(); ++c)
2705 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002706 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002707 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002708 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002709 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002710 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002711
Bas Nieuwenhuizenc9ffeec2020-09-03 03:09:39 +02002712 if (node->getType().getQualifier().isNonUniform()) {
2713 builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
2714 }
2715
John Kessenich140f3df2015-06-26 16:58:36 -06002716 builder.clearAccessChain();
2717 builder.setAccessChainRValue(constructed);
2718
2719 return false;
2720 }
2721
2722 // These six are component-wise compares with component-wise results.
2723 // Forward on to createBinaryOperation(), requesting a vector result.
2724 case glslang::EOpLessThan:
2725 case glslang::EOpGreaterThan:
2726 case glslang::EOpLessThanEqual:
2727 case glslang::EOpGreaterThanEqual:
2728 case glslang::EOpVectorEqual:
2729 case glslang::EOpVectorNotEqual:
2730 {
2731 // Map the operation to a binary
2732 binOp = node->getOp();
2733 reduceComparison = false;
2734 switch (node->getOp()) {
2735 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2736 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2737 default: binOp = node->getOp(); break;
2738 }
2739
2740 break;
2741 }
2742 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002743 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002744 binOp = glslang::EOpMul;
2745 break;
2746 case glslang::EOpOuterProduct:
2747 // two vectors multiplied to make a matrix
2748 binOp = glslang::EOpOuterProduct;
2749 break;
2750 case glslang::EOpDot:
2751 {
qining25262b32016-05-06 17:25:16 -04002752 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002753 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002754 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002755 binOp = glslang::EOpMul;
2756 break;
2757 }
2758 case glslang::EOpMod:
2759 // when an aggregate, this is the floating-point mod built-in function,
2760 // which can be emitted by the one in createBinaryOperation()
2761 binOp = glslang::EOpMod;
2762 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002763
John Kessenich140f3df2015-06-26 16:58:36 -06002764 case glslang::EOpEmitVertex:
2765 case glslang::EOpEndPrimitive:
2766 case glslang::EOpBarrier:
2767 case glslang::EOpMemoryBarrier:
2768 case glslang::EOpMemoryBarrierAtomicCounter:
2769 case glslang::EOpMemoryBarrierBuffer:
2770 case glslang::EOpMemoryBarrierImage:
2771 case glslang::EOpMemoryBarrierShared:
2772 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002773 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002774 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002775 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002776 case glslang::EOpWorkgroupMemoryBarrier:
2777 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002778 case glslang::EOpSubgroupBarrier:
2779 case glslang::EOpSubgroupMemoryBarrier:
2780 case glslang::EOpSubgroupMemoryBarrierBuffer:
2781 case glslang::EOpSubgroupMemoryBarrierImage:
2782 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002783 noReturnValue = true;
2784 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2785 break;
2786
John Kessenich426394d2015-07-23 10:22:48 -06002787 case glslang::EOpAtomicAdd:
greg-lunarg4e064ee2021-03-15 11:26:11 -06002788 case glslang::EOpAtomicSubtract:
John Kessenich426394d2015-07-23 10:22:48 -06002789 case glslang::EOpAtomicMin:
2790 case glslang::EOpAtomicMax:
2791 case glslang::EOpAtomicAnd:
2792 case glslang::EOpAtomicOr:
2793 case glslang::EOpAtomicXor:
2794 case glslang::EOpAtomicExchange:
2795 case glslang::EOpAtomicCompSwap:
2796 atomic = true;
2797 break;
2798
John Kesseniche5eee8f2019-10-18 01:03:11 -06002799#ifndef GLSLANG_WEB
2800 case glslang::EOpAtomicStore:
2801 noReturnValue = true;
2802 // fallthrough
2803 case glslang::EOpAtomicLoad:
2804 atomic = true;
2805 break;
2806
John Kessenich0d0c6d32017-07-23 16:08:26 -06002807 case glslang::EOpAtomicCounterAdd:
2808 case glslang::EOpAtomicCounterSubtract:
2809 case glslang::EOpAtomicCounterMin:
2810 case glslang::EOpAtomicCounterMax:
2811 case glslang::EOpAtomicCounterAnd:
2812 case glslang::EOpAtomicCounterOr:
2813 case glslang::EOpAtomicCounterXor:
2814 case glslang::EOpAtomicCounterExchange:
2815 case glslang::EOpAtomicCounterCompSwap:
2816 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2817 builder.addCapability(spv::CapabilityAtomicStorageOps);
2818 atomic = true;
2819 break;
2820
Ian Romanickb3bd4022019-01-21 08:57:25 -08002821 case glslang::EOpAbsDifference:
2822 case glslang::EOpAddSaturate:
2823 case glslang::EOpSubSaturate:
2824 case glslang::EOpAverage:
2825 case glslang::EOpAverageRounded:
2826 case glslang::EOpMul32x16:
2827 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2828 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2829 binOp = node->getOp();
2830 break;
2831
Daniel Kochffccefd2020-11-23 15:41:27 -05002832 case glslang::EOpIgnoreIntersectionNV:
2833 case glslang::EOpTerminateRayNV:
2834 case glslang::EOpTraceNV:
2835 case glslang::EOpTraceKHR:
2836 case glslang::EOpExecuteCallableNV:
2837 case glslang::EOpExecuteCallableKHR:
Chao Chen3c366992018-09-19 11:41:59 -07002838 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2839 noReturnValue = true;
2840 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002841 case glslang::EOpRayQueryInitialize:
2842 case glslang::EOpRayQueryTerminate:
2843 case glslang::EOpRayQueryGenerateIntersection:
2844 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002845 builder.addExtension("SPV_KHR_ray_query");
Daniel Kochffccefd2020-11-23 15:41:27 -05002846 builder.addCapability(spv::CapabilityRayQueryKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002847 noReturnValue = true;
2848 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002849 case glslang::EOpRayQueryProceed:
2850 case glslang::EOpRayQueryGetIntersectionType:
2851 case glslang::EOpRayQueryGetRayTMin:
2852 case glslang::EOpRayQueryGetRayFlags:
2853 case glslang::EOpRayQueryGetIntersectionT:
2854 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2855 case glslang::EOpRayQueryGetIntersectionInstanceId:
2856 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2857 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2858 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2859 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2860 case glslang::EOpRayQueryGetIntersectionFrontFace:
2861 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2862 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2863 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2864 case glslang::EOpRayQueryGetWorldRayDirection:
2865 case glslang::EOpRayQueryGetWorldRayOrigin:
2866 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2867 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2868 builder.addExtension("SPV_KHR_ray_query");
Daniel Kochffccefd2020-11-23 15:41:27 -05002869 builder.addCapability(spv::CapabilityRayQueryKHR);
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002870 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002871 case glslang::EOpCooperativeMatrixLoad:
2872 case glslang::EOpCooperativeMatrixStore:
2873 noReturnValue = true;
2874 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002875 case glslang::EOpBeginInvocationInterlock:
2876 case glslang::EOpEndInvocationInterlock:
2877 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2878 noReturnValue = true;
2879 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002880#endif
Chao Chen3c366992018-09-19 11:41:59 -07002881
Jeff Bolz04d73732019-05-31 13:06:01 -05002882 case glslang::EOpDebugPrintf:
2883 noReturnValue = true;
2884 break;
2885
John Kessenich140f3df2015-06-26 16:58:36 -06002886 default:
2887 break;
2888 }
2889
2890 //
2891 // See if it maps to a regular operation.
2892 //
John Kessenich140f3df2015-06-26 16:58:36 -06002893 if (binOp != glslang::EOpNull) {
2894 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2895 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2896 assert(left && right);
2897
2898 builder.clearAccessChain();
2899 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002900 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002901
2902 builder.clearAccessChain();
2903 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002904 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002905
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002906 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002907 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002908 TranslateNoContractionDecoration(node->getType().getQualifier()),
2909 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002910 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002911 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002912 left->getType().getBasicType(), reduceComparison);
2913
2914 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002915 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002916 builder.clearAccessChain();
2917 builder.setAccessChainRValue(result);
2918
2919 return false;
2920 }
2921
John Kessenich426394d2015-07-23 10:22:48 -06002922 //
2923 // Create the list of operands.
2924 //
John Kessenich140f3df2015-06-26 16:58:36 -06002925 glslang::TIntermSequence& glslangOperands = node->getSequence();
2926 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002927 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002928 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002929 // special case l-value operands; there are just a few
2930 bool lvalue = false;
2931 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002932 case glslang::EOpModf:
2933 if (arg == 1)
2934 lvalue = true;
2935 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002936
Torosdagli06c2eee2020-03-19 11:09:57 -04002937 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002938 case glslang::EOpRayQueryTerminate:
2939 case glslang::EOpRayQueryConfirmIntersection:
2940 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002941 case glslang::EOpRayQueryGenerateIntersection:
2942 case glslang::EOpRayQueryGetIntersectionType:
2943 case glslang::EOpRayQueryGetIntersectionT:
2944 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2945 case glslang::EOpRayQueryGetIntersectionInstanceId:
2946 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2947 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2948 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2949 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2950 case glslang::EOpRayQueryGetIntersectionFrontFace:
2951 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2952 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2953 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2954 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2955 if (arg == 0)
2956 lvalue = true;
2957 break;
2958
John Kesseniche5eee8f2019-10-18 01:03:11 -06002959 case glslang::EOpAtomicAdd:
greg-lunarg4e064ee2021-03-15 11:26:11 -06002960 case glslang::EOpAtomicSubtract:
John Kesseniche5eee8f2019-10-18 01:03:11 -06002961 case glslang::EOpAtomicMin:
2962 case glslang::EOpAtomicMax:
2963 case glslang::EOpAtomicAnd:
2964 case glslang::EOpAtomicOr:
2965 case glslang::EOpAtomicXor:
2966 case glslang::EOpAtomicExchange:
2967 case glslang::EOpAtomicCompSwap:
2968 if (arg == 0)
2969 lvalue = true;
2970 break;
2971
John Kessenicha28f7a72019-08-06 07:00:58 -06002972#ifndef GLSLANG_WEB
2973 case glslang::EOpFrexp:
2974 if (arg == 1)
2975 lvalue = true;
2976 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002977 case glslang::EOpInterpolateAtSample:
2978 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002979 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002980 if (arg == 0) {
Greg Fischer7fbaca02021-03-31 15:24:48 -06002981 // If GLSL, use the address of the interpolant argument.
2982 // If HLSL, use an internal version of OpInterolates that takes
2983 // the rvalue of the interpolant. A fixup pass in spirv-opt
2984 // legalization will remove the OpLoad and convert to an lvalue.
2985 // Had to do this because legalization will only propagate a
2986 // builtin into an rvalue.
2987 lvalue = glslangIntermediate->getSource() != glslang::EShSourceHlsl;
John Kessenich8c8505c2016-07-26 12:50:38 -06002988
2989 // Does it need a swizzle inversion? If so, evaluation is inverted;
2990 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002991 // That is, we transform
2992 //
2993 // interpolate(v.zy) -> interpolate(v).zy
2994 //
John Kessenichecba76f2017-01-06 00:34:48 -07002995 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002996 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002997 invertedType = convertGlslangToSpvType(
2998 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002999 }
Rex Xu7a26c172015-12-08 17:12:09 +08003000 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05003001 case glslang::EOpAtomicLoad:
3002 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06003003 case glslang::EOpAtomicCounterAdd:
3004 case glslang::EOpAtomicCounterSubtract:
3005 case glslang::EOpAtomicCounterMin:
3006 case glslang::EOpAtomicCounterMax:
3007 case glslang::EOpAtomicCounterAnd:
3008 case glslang::EOpAtomicCounterOr:
3009 case glslang::EOpAtomicCounterXor:
3010 case glslang::EOpAtomicCounterExchange:
3011 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08003012 if (arg == 0)
3013 lvalue = true;
3014 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003015 case glslang::EOpAddCarry:
3016 case glslang::EOpSubBorrow:
3017 if (arg == 2)
3018 lvalue = true;
3019 break;
3020 case glslang::EOpUMulExtended:
3021 case glslang::EOpIMulExtended:
3022 if (arg >= 2)
3023 lvalue = true;
3024 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003025 case glslang::EOpCooperativeMatrixLoad:
3026 if (arg == 0 || arg == 1)
3027 lvalue = true;
3028 break;
3029 case glslang::EOpCooperativeMatrixStore:
3030 if (arg == 1)
3031 lvalue = true;
3032 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003033#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003034 default:
3035 break;
3036 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003037 builder.clearAccessChain();
3038 if (invertedType != spv::NoType && arg == 0)
3039 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
3040 else
3041 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003042
John Kessenichb9197c82019-08-11 07:41:45 -06003043#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003044 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
3045 node->getOp() == glslang::EOpCooperativeMatrixStore) {
3046
3047 if (arg == 1) {
3048 // fold "element" parameter into the access chain
3049 spv::Builder::AccessChain save = builder.getAccessChain();
3050 builder.clearAccessChain();
3051 glslangOperands[2]->traverse(this);
3052
3053 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
3054
3055 builder.setAccessChain(save);
3056
3057 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07003058 builder.accessChainPush(elementId,
3059 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
3060 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003061
3062 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3063 unsigned int alignment = builder.getAccessChain().alignment;
3064
3065 int memoryAccess = TranslateMemoryAccess(coherentFlags);
3066 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
3067 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
3068 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
3069 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07003070 if (builder.getStorageClass(builder.getAccessChain().base) ==
3071 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003072 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
3073 }
3074
3075 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
3076
3077 if (memoryAccess & spv::MemoryAccessAlignedMask) {
3078 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
3079 }
3080
John Kessenich8985fc92020-03-03 10:25:07 -07003081 if (memoryAccess &
3082 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
3083 memoryAccessOperands.push_back(spv::IdImmediate(true,
3084 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003085 }
3086 } else if (arg == 2) {
3087 continue;
3088 }
3089 }
John Kessenichb9197c82019-08-11 07:41:45 -06003090#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003091
John Kessenichbbbd9a22020-03-03 07:21:37 -07003092 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003093 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07003094 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
3095 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
3096 // reduce to a simple access chain. So, we need a temporary vector to
3097 // receive the result, and must later swizzle that into the original
3098 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06003099 complexLvalues.push_back(builder.getAccessChain());
John Kessenich435dd802020-06-30 01:27:08 -06003100 temporaryLvalues.push_back(builder.createVariable(
3101 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003102 builder.accessChainGetInferredType(), "swizzleTemp"));
3103 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003104 } else {
3105 operands.push_back(builder.accessChainGetLValue());
3106 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003107 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3108 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3109 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003110 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003111 glslang::TOperator glslangOp = node->getOp();
3112 if (arg == 1 &&
3113 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3114 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3115 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3116 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3117 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3118 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3119 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3120 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3121 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3122 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3123 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3124 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3125 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3126 )) {
3127 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3128 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
Daniel Kochffccefd2020-11-23 15:41:27 -05003129 } else if ((arg == 10 && glslangOp == glslang::EOpTraceKHR) ||
3130 (arg == 1 && glslangOp == glslang::EOpExecuteCallableKHR)) {
3131 const int opdNum = glslangOp == glslang::EOpTraceKHR ? 10 : 1;
3132 const int set = glslangOp == glslang::EOpTraceKHR ? 0 : 1;
3133 const int location = glslangOperands[opdNum]->getAsConstantUnion()->getConstArray()[0].getUConst();
3134 auto itNode = locationToSymbol[set].find(location);
3135 visitSymbol(itNode->second);
3136 spv::Id symId = getSymbolId(itNode->second);
3137 operands.push_back(symId);
3138 } else {
Torosdagli06c2eee2020-03-19 11:09:57 -04003139 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
Daniel Kochffccefd2020-11-23 15:41:27 -05003140 }
John Kesseniche485c7a2017-05-31 18:50:53 -06003141 }
John Kessenich140f3df2015-06-26 16:58:36 -06003142 }
John Kessenich426394d2015-07-23 10:22:48 -06003143
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003144 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003145#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003146 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3147 std::vector<spv::IdImmediate> idImmOps;
3148
3149 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3150 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3151 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3152 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3153 // get the pointee type
3154 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3155 assert(builder.isCooperativeMatrixType(typeId));
3156 // do the op
3157 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3158 // store the result to the pointer (out param 'm')
3159 builder.createStore(result, operands[0]);
3160 result = 0;
3161 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3162 std::vector<spv::IdImmediate> idImmOps;
3163
3164 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3165 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3166 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3167 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3168 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3169
3170 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3171 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003172 } else
3173#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003174 if (atomic) {
3175 // Handle all atomics
Greg Fischerb5c8fd42021-03-08 14:02:06 -07003176 glslang::TBasicType typeProxy = (node->getOp() == glslang::EOpAtomicStore)
3177 ? node->getSequence()[0]->getAsTyped()->getBasicType() : node->getBasicType();
3178 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, typeProxy,
John Kessenich8985fc92020-03-03 10:25:07 -07003179 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003180 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3181 if (!nonSemanticDebugPrintf) {
3182 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3183 }
3184 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3185 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003186 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003187 // Pass through to generic operations.
3188 switch (glslangOperands.size()) {
3189 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003190 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003191 break;
3192 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003193 {
3194 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003195 TranslateNoContractionDecoration(node->getType().getQualifier()),
3196 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003197 result = createUnaryOperation(
3198 node->getOp(), decorations,
3199 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003200 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003201 }
John Kessenich426394d2015-07-23 10:22:48 -06003202 break;
3203 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003204 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003205 break;
3206 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003207
John Kessenichbbbd9a22020-03-03 07:21:37 -07003208 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003209 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003210
3211 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3212 builder.setAccessChain(complexLvalues[i]);
greg-lunarg639f5462020-11-12 11:10:07 -07003213 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision),
3214 TranslateNonUniformDecoration(complexLvalues[i].coherentFlags));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003215 }
John Kessenich140f3df2015-06-26 16:58:36 -06003216 }
3217
3218 if (noReturnValue)
3219 return false;
3220
3221 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003222 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003223 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003224 } else {
3225 builder.clearAccessChain();
3226 builder.setAccessChainRValue(result);
3227 return false;
3228 }
3229}
3230
John Kessenich433e9ff2017-01-26 20:31:11 -07003231// This path handles both if-then-else and ?:
3232// The if-then-else has a node type of void, while
3233// ?: has either a void or a non-void node type
3234//
3235// Leaving the result, when not void:
3236// GLSL only has r-values as the result of a :?, but
3237// if we have an l-value, that can be more efficient if it will
3238// become the base of a complex r-value expression, because the
3239// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003240bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3241{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003242 // see if OpSelect can handle it
3243 const auto isOpSelectable = [&]() {
3244 if (node->getBasicType() == glslang::EbtVoid)
3245 return false;
3246 // OpSelect can do all other types starting with SPV 1.4
3247 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3248 // pre-1.4, only scalars and vectors can be handled
3249 if ((!node->getType().isScalar() && !node->getType().isVector()))
3250 return false;
3251 }
3252 return true;
3253 };
3254
John Kessenich4bee5312018-02-20 21:29:05 -07003255 // See if it simple and safe, or required, to execute both sides.
3256 // Crucially, side effects must be either semantically required or avoided,
3257 // and there are performance trade-offs.
3258 // Return true if required or a good idea (and safe) to execute both sides,
3259 // false otherwise.
3260 const auto bothSidesPolicy = [&]() -> bool {
3261 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003262 if (node->getTrueBlock() == nullptr ||
3263 node->getFalseBlock() == nullptr)
3264 return false;
3265
John Kessenich4bee5312018-02-20 21:29:05 -07003266 // required? (unless we write additional code to look for side effects
3267 // and make performance trade-offs if none are present)
3268 if (!node->getShortCircuit())
3269 return true;
3270
3271 // if not required to execute both, decide based on performance/practicality...
3272
John Kessenich0c1e71a2019-01-10 18:23:06 +07003273 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003274 return false;
3275
John Kessenich433e9ff2017-01-26 20:31:11 -07003276 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3277 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3278
3279 // return true if a single operand to ? : is okay for OpSelect
3280 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003281 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003282 };
3283
3284 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3285 operandOkay(node->getFalseBlock()->getAsTyped());
3286 };
3287
John Kessenich4bee5312018-02-20 21:29:05 -07003288 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3289 // emit the condition before doing anything with selection
3290 node->getCondition()->traverse(this);
3291 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3292
3293 // Find a way of executing both sides and selecting the right result.
3294 const auto executeBothSides = [&]() -> void {
3295 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003296 node->getTrueBlock()->traverse(this);
3297 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3298 node->getFalseBlock()->traverse(this);
3299 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3300
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003301 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003302
John Kessenich4bee5312018-02-20 21:29:05 -07003303 // done if void
3304 if (node->getBasicType() == glslang::EbtVoid)
3305 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003306
John Kessenich4bee5312018-02-20 21:29:05 -07003307 // emit code to select between trueValue and falseValue
3308
3309 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003310 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003311 // Emit OpSelect for this selection.
3312
3313 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003314 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3315 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003316 condition = builder.smearScalar(spv::NoPrecision, condition,
3317 builder.makeVectorType(builder.makeBoolType(),
3318 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003319 }
John Kessenich4bee5312018-02-20 21:29:05 -07003320
3321 // OpSelect
3322 result = builder.createTriOp(spv::OpSelect,
3323 convertGlslangToSpvType(node->getType()), condition,
3324 trueValue, falseValue);
3325
3326 builder.clearAccessChain();
3327 builder.setAccessChainRValue(result);
3328 } else {
3329 // We need control flow to select the result.
3330 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003331 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3332 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003333
3334 // Selection control:
3335 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3336
3337 // make an "if" based on the value created by the condition
3338 spv::Builder::If ifBuilder(condition, control, builder);
3339
3340 // emit the "then" statement
3341 builder.createStore(trueValue, result);
3342 ifBuilder.makeBeginElse();
3343 // emit the "else" statement
3344 builder.createStore(falseValue, result);
3345
3346 // finish off the control flow
3347 ifBuilder.makeEndIf();
3348
3349 builder.clearAccessChain();
3350 builder.setAccessChainLValue(result);
3351 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003352 };
3353
John Kessenich4bee5312018-02-20 21:29:05 -07003354 // Execute the one side needed, as per the condition
3355 const auto executeOneSide = [&]() {
3356 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003357 if (node->getBasicType() != glslang::EbtVoid) {
3358 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3359 convertGlslangToSpvType(node->getType()));
3360 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003361
John Kessenich4bee5312018-02-20 21:29:05 -07003362 // Selection control:
3363 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3364
3365 // make an "if" based on the value created by the condition
3366 spv::Builder::If ifBuilder(condition, control, builder);
3367
3368 // emit the "then" statement
3369 if (node->getTrueBlock() != nullptr) {
3370 node->getTrueBlock()->traverse(this);
3371 if (result != spv::NoResult)
3372 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3373 }
3374
3375 if (node->getFalseBlock() != nullptr) {
3376 ifBuilder.makeBeginElse();
3377 // emit the "else" statement
3378 node->getFalseBlock()->traverse(this);
3379 if (result != spv::NoResult)
3380 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3381 }
3382
3383 // finish off the control flow
3384 ifBuilder.makeEndIf();
3385
3386 if (result != spv::NoResult) {
3387 builder.clearAccessChain();
3388 builder.setAccessChainLValue(result);
3389 }
3390 };
3391
3392 // Try for OpSelect (or a requirement to execute both sides)
3393 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003394 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3395 if (node->getType().getQualifier().isSpecConstant())
3396 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003397 executeBothSides();
3398 } else
3399 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003400
3401 return false;
3402}
3403
3404bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3405{
3406 // emit and get the condition before doing anything with switch
3407 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003408 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003409
Rex Xu57e65922017-07-04 23:23:40 +08003410 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003411 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003412
John Kessenich140f3df2015-06-26 16:58:36 -06003413 // browse the children to sort out code segments
3414 int defaultSegment = -1;
3415 std::vector<TIntermNode*> codeSegments;
3416 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3417 std::vector<int> caseValues;
3418 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3419 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3420 TIntermNode* child = *c;
3421 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003422 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003423 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003424 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003425 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3426 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003427 } else
3428 codeSegments.push_back(child);
3429 }
3430
qining25262b32016-05-06 17:25:16 -04003431 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003432 // statements between the last case and the end of the switch statement
3433 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3434 (int)codeSegments.size() == defaultSegment)
3435 codeSegments.push_back(nullptr);
3436
3437 // make the switch statement
3438 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003439 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3440 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003441
3442 // emit all the code in the segments
3443 breakForLoop.push(false);
3444 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3445 builder.nextSwitchSegment(segmentBlocks, s);
3446 if (codeSegments[s])
3447 codeSegments[s]->traverse(this);
3448 else
3449 builder.addSwitchBreak();
3450 }
3451 breakForLoop.pop();
3452
3453 builder.endSwitch(segmentBlocks);
3454
3455 return false;
3456}
3457
3458void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3459{
3460 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003461 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003462
3463 builder.clearAccessChain();
3464 builder.setAccessChainRValue(constant);
3465}
3466
3467bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3468{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003469 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003470 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003471
3472 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003473 std::vector<unsigned int> operands;
3474 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003475
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003476 // Spec requires back edges to target header blocks, and every header block
3477 // must dominate its merge block. Make a header block first to ensure these
3478 // conditions are met. By definition, it will contain OpLoopMerge, followed
3479 // by a block-ending branch. But we don't want to put any other body/test
3480 // instructions in it, since the body/test may have arbitrary instructions,
3481 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003482 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003483 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003484 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003485 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003486 spv::Block& test = builder.makeNewBlock();
3487 builder.createBranch(&test);
3488
3489 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003490 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003491 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003492 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3493
3494 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003495 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003496 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003497 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003498 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003499 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003500
3501 builder.setBuildPoint(&blocks.continue_target);
3502 if (node->getTerminal())
3503 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003504 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003505 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003506 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003507 builder.createBranch(&blocks.body);
3508
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003509 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003510 builder.setBuildPoint(&blocks.body);
3511 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003512 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003513 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003514 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003515
3516 builder.setBuildPoint(&blocks.continue_target);
3517 if (node->getTerminal())
3518 node->getTerminal()->traverse(this);
3519 if (node->getTest()) {
3520 node->getTest()->traverse(this);
3521 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003522 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003523 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003524 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003525 // TODO: unless there was a break/return/discard instruction
3526 // somewhere in the body, this is an infinite loop, so we should
3527 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003528 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003529 }
John Kessenich140f3df2015-06-26 16:58:36 -06003530 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003531 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003532 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003533 return false;
3534}
3535
3536bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3537{
3538 if (node->getExpression())
3539 node->getExpression()->traverse(this);
3540
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003541 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003542
John Kessenich140f3df2015-06-26 16:58:36 -06003543 switch (node->getFlowOp()) {
3544 case glslang::EOpKill:
Daniel Kochffccefd2020-11-23 15:41:27 -05003545 builder.makeStatementTerminator(spv::OpKill, "post-discard");
John Kessenich140f3df2015-06-26 16:58:36 -06003546 break;
Jesse Hall74e8f052020-11-09 08:30:01 -08003547 case glslang::EOpTerminateInvocation:
3548 builder.addExtension(spv::E_SPV_KHR_terminate_invocation);
Daniel Kochffccefd2020-11-23 15:41:27 -05003549 builder.makeStatementTerminator(spv::OpTerminateInvocation, "post-terminate-invocation");
Jesse Hall74e8f052020-11-09 08:30:01 -08003550 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003551 case glslang::EOpBreak:
3552 if (breakForLoop.top())
3553 builder.createLoopExit();
3554 else
3555 builder.addSwitchBreak();
3556 break;
3557 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003558 builder.createLoopContinue();
3559 break;
3560 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003561 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003562 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3563 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003564 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3565 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003566 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003567 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3568 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003569 builder.setAccessChainLValue(copyId);
3570 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003571 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003572 }
3573 builder.makeReturn(false, returnId);
3574 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003575 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003576
3577 builder.clearAccessChain();
3578 break;
3579
John Kessenichb9197c82019-08-11 07:41:45 -06003580#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003581 case glslang::EOpDemote:
3582 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3583 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3584 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3585 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05003586 case glslang::EOpTerminateRayKHR:
3587 builder.makeStatementTerminator(spv::OpTerminateRayKHR, "post-terminateRayKHR");
3588 break;
3589 case glslang::EOpIgnoreIntersectionKHR:
3590 builder.makeStatementTerminator(spv::OpIgnoreIntersectionKHR, "post-ignoreIntersectionKHR");
3591 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003592#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003593
John Kessenich140f3df2015-06-26 16:58:36 -06003594 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003595 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003596 break;
3597 }
3598
3599 return false;
3600}
3601
John Kessenich9c14f772019-06-17 08:38:35 -06003602spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003603{
qining25262b32016-05-06 17:25:16 -04003604 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003605 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003606 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003607 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003608 spv::Id result = createSpvConstant(*node);
3609 if (result != spv::NoResult)
3610 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003611 }
3612
3613 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003614 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003615 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3616 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003617
John Kessenichb9197c82019-08-11 07:41:45 -06003618 const bool contains16BitType = node->getType().contains16BitFloat() ||
3619 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003620 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003621 switch (storageClass) {
3622 case spv::StorageClassInput:
3623 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003624 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003625 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003626 break;
John Kessenich18310872018-05-14 22:08:53 -06003627 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003628 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003629 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3630 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003631 else
3632 builder.addCapability(spv::CapabilityStorageUniform16);
3633 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003634#ifndef GLSLANG_WEB
3635 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003636 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003637 builder.addCapability(spv::CapabilityStoragePushConstant16);
3638 break;
John Kessenich18310872018-05-14 22:08:53 -06003639 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003640 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003641 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003642 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3643 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003644#endif
John Kessenich18310872018-05-14 22:08:53 -06003645 default:
Caio Marcelo de Oliveira Filho4bfbf622020-06-02 16:58:51 -07003646 if (storageClass == spv::StorageClassWorkgroup &&
3647 node->getType().getBasicType() == glslang::EbtBlock) {
3648 builder.addCapability(spv::CapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR);
3649 break;
3650 }
John Kessenichb9197c82019-08-11 07:41:45 -06003651 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003652 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003653 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003654 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003655 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003656 }
3657 }
Rex Xuf89ad982017-04-07 23:22:33 +08003658
John Kessenichb9197c82019-08-11 07:41:45 -06003659 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003660 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003661 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003662 builder.addCapability(spv::CapabilityStoragePushConstant8);
3663 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003664 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003665 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003666 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003667 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003668 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Caio Marcelo de Oliveira Filho4bfbf622020-06-02 16:58:51 -07003669 } else if (storageClass == spv::StorageClassWorkgroup &&
3670 node->getType().getBasicType() == glslang::EbtBlock) {
3671 builder.addCapability(spv::CapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003672 } else {
3673 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003674 }
3675 }
3676
John Kessenich140f3df2015-06-26 16:58:36 -06003677 const char* name = node->getName().c_str();
3678 if (glslang::IsAnonymous(name))
3679 name = "";
3680
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003681 spv::Id initializer = spv::NoResult;
3682
John Kessenichc739e032020-06-11 08:30:03 -06003683 if (node->getType().getQualifier().storage == glslang::EvqUniform && !node->getConstArray().empty()) {
3684 int nextConst = 0;
3685 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3686 node->getConstArray(),
3687 nextConst,
3688 false /* specConst */);
3689 } else if (node->getType().getQualifier().isNullInit()) {
3690 initializer = builder.makeNullConstant(spvType);
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003691 }
3692
John Kessenich435dd802020-06-30 01:27:08 -06003693 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003694}
3695
3696// Return type Id of the sampled type.
3697spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3698{
3699 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003700 case glslang::EbtInt: return builder.makeIntType(32);
3701 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003702 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003703#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003704 case glslang::EbtFloat16:
3705 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3706 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3707 return builder.makeFloatType(16);
Tobski8c1a3a02020-11-04 16:24:23 +00003708 case glslang::EbtInt64: return builder.makeIntType(64);
3709 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3710 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3711 case glslang::EbtUint64: return builder.makeUintType(64);
3712 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3713 builder.addCapability(spv::CapabilityFloat16ImageAMD);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003714#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003715 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003716 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003717 return builder.makeFloatType(32);
3718 }
3719}
3720
John Kessenich8c8505c2016-07-26 12:50:38 -06003721// If node is a swizzle operation, return the type that should be used if
3722// the swizzle base is first consumed by another operation, before the swizzle
3723// is applied.
3724spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3725{
John Kessenichecba76f2017-01-06 00:34:48 -07003726 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003727 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3728 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3729 else
3730 return spv::NoType;
3731}
3732
3733// When inverting a swizzle with a parent op, this function
3734// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003735spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3736 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003737{
3738 std::vector<unsigned> swizzle;
3739 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3740 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3741}
3742
John Kessenich8c8505c2016-07-26 12:50:38 -06003743// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3744void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3745{
3746 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3747 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3748 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3749}
3750
John Kessenich3ac051e2015-12-20 11:29:16 -07003751// Convert from a glslang type to an SPV type, by calling into a
3752// recursive version of this function. This establishes the inherited
3753// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003754spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003755{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003756 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003757}
3758
3759// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003760// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003761// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003762spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003763 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3764 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003765{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003766 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003767
3768 switch (type.getBasicType()) {
3769 case glslang::EbtVoid:
3770 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003771 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003772 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003773 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003774 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3775 // a 32-bit int where non-0 means true.
3776 if (explicitLayout != glslang::ElpNone)
3777 spvType = builder.makeUintType(32);
3778 else
3779 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003780 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003781 case glslang::EbtInt:
3782 spvType = builder.makeIntType(32);
3783 break;
3784 case glslang::EbtUint:
3785 spvType = builder.makeUintType(32);
3786 break;
3787 case glslang::EbtFloat:
3788 spvType = builder.makeFloatType(32);
3789 break;
3790#ifndef GLSLANG_WEB
3791 case glslang::EbtDouble:
3792 spvType = builder.makeFloatType(64);
3793 break;
3794 case glslang::EbtFloat16:
3795 spvType = builder.makeFloatType(16);
3796 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003797 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003798 spvType = builder.makeIntType(8);
3799 break;
3800 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003801 spvType = builder.makeUintType(8);
3802 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003803 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003804 spvType = builder.makeIntType(16);
3805 break;
3806 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003807 spvType = builder.makeUintType(16);
3808 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003809 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003810 spvType = builder.makeIntType(64);
3811 break;
3812 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003813 spvType = builder.makeUintType(64);
3814 break;
John Kessenich426394d2015-07-23 10:22:48 -06003815 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003816 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003817 spvType = builder.makeUintType(32);
3818 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003819 case glslang::EbtAccStruct:
Daniel Koch4d41da32020-11-24 23:06:16 -05003820 switch (glslangIntermediate->getStage()) {
3821 case EShLangRayGen:
3822 case EShLangIntersect:
3823 case EShLangAnyHit:
3824 case EShLangClosestHit:
3825 case EShLangMiss:
3826 case EShLangCallable:
3827 // these all should have the RayTracingNV/KHR capability already
3828 break;
3829 default:
3830 {
3831 auto& extensions = glslangIntermediate->getRequestedExtensions();
3832 if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
3833 builder.addExtension(spv::E_SPV_KHR_ray_query);
3834 builder.addCapability(spv::CapabilityRayQueryKHR);
3835 }
3836 }
3837 break;
3838 }
Daniel Kochdb32b242020-03-17 20:42:47 -04003839 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003840 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003841 case glslang::EbtRayQuery:
Daniel Koch4d41da32020-11-24 23:06:16 -05003842 {
3843 auto& extensions = glslangIntermediate->getRequestedExtensions();
3844 if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
3845 builder.addExtension(spv::E_SPV_KHR_ray_query);
3846 builder.addCapability(spv::CapabilityRayQueryKHR);
3847 }
3848 spvType = builder.makeRayQueryType();
3849 }
Torosdagli06c2eee2020-03-19 11:09:57 -04003850 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003851 case glslang::EbtReference:
3852 {
3853 // Make the forward pointer, then recurse to convert the structure type, then
3854 // patch up the forward pointer with a real pointer type.
3855 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3856 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3857 forwardPointers[type.getReferentType()] = forwardId;
3858 }
3859 spvType = forwardPointers[type.getReferentType()];
3860 if (!forwardReferenceOnly) {
3861 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3862 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3863 forwardPointers[type.getReferentType()],
3864 referentType);
3865 }
3866 }
3867 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003868#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003869 case glslang::EbtSampler:
3870 {
3871 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003872 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003873 spvType = builder.makeSamplerType();
3874 } else {
3875 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003876 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3877 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3878 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3879 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003880 // already has both image and sampler, make the combined type
3881 spvType = builder.makeSampledImageType(spvType);
3882 }
John Kessenich55e7d112015-11-15 21:33:39 -07003883 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003884 }
John Kessenich140f3df2015-06-26 16:58:36 -06003885 break;
3886 case glslang::EbtStruct:
3887 case glslang::EbtBlock:
3888 {
3889 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003890 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003891
3892 // Try to share structs for different layouts, but not yet for other
3893 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003894 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003895 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003896 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003897 break;
3898
3899 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003900 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003901 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003902 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003903 }
3904 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003905 case glslang::EbtString:
3906 // no type used for OpString
3907 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003908 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003909 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003910 break;
3911 }
3912
3913 if (type.isMatrix())
3914 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3915 else {
3916 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3917 if (type.getVectorSize() > 1)
3918 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3919 }
3920
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003921 if (type.isCoopMat()) {
3922 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3923 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3924 if (type.getBasicType() == glslang::EbtFloat16)
3925 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003926 if (type.getBasicType() == glslang::EbtUint8 ||
3927 type.getBasicType() == glslang::EbtInt8) {
3928 builder.addCapability(spv::CapabilityInt8);
3929 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003930
3931 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3932 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3933 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3934
3935 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3936 }
3937
John Kessenich140f3df2015-06-26 16:58:36 -06003938 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003939 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3940
John Kessenichc9a80832015-09-12 12:17:44 -06003941 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003942 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003943 // We need to decorate array strides for types needing explicit layout, except blocks.
3944 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003945 // Use a dummy glslang type for querying internal strides of
3946 // arrays of arrays, but using just a one-dimensional array.
3947 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003948 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3949 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003950
3951 // Will compute the higher-order strides here, rather than making a whole
3952 // pile of types and doing repetitive recursion on their contents.
3953 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3954 }
John Kessenichf8842e52016-01-04 19:22:56 -07003955
3956 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003957 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003958 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003959 if (stride > 0)
3960 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003961 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003962 }
3963 } else {
3964 // single-dimensional array, and don't yet have stride
3965
John Kessenichf8842e52016-01-04 19:22:56 -07003966 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003967 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3968 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003969 }
John Kessenich31ed4832015-09-09 17:51:38 -06003970
John Kessenichead86222018-03-28 18:01:20 -06003971 // Do the outer dimension, which might not be known for a runtime-sized array.
3972 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3973 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003974 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003975 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003976#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003977 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003978 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003979 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3980 }
John Kessenichb9197c82019-08-11 07:41:45 -06003981#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003982 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003983 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003984 if (stride > 0)
3985 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003986 }
3987
3988 return spvType;
3989}
3990
John Kessenich0e737842017-03-24 18:38:16 -06003991// TODO: this functionality should exist at a higher level, in creating the AST
3992//
3993// Identify interface members that don't have their required extension turned on.
3994//
3995bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3996{
John Kessenicha28f7a72019-08-06 07:00:58 -06003997#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003998 auto& extensions = glslangIntermediate->getRequestedExtensions();
3999
Rex Xubcf291a2017-03-29 23:01:36 +08004000 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
4001 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
4002 return true;
John Kessenich0e737842017-03-24 18:38:16 -06004003 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
4004 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
4005 return true;
Chao Chen3c366992018-09-19 11:41:59 -07004006
4007 if (glslangIntermediate->getStage() != EShLangMeshNV) {
4008 if (member.getFieldName() == "gl_ViewportMask" &&
4009 extensions.find("GL_NV_viewport_array2") == extensions.end())
4010 return true;
4011 if (member.getFieldName() == "gl_PositionPerViewNV" &&
4012 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
4013 return true;
4014 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
4015 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
4016 return true;
4017 }
4018#endif
John Kessenich0e737842017-03-24 18:38:16 -06004019
4020 return false;
4021};
4022
John Kessenich6090df02016-06-30 21:18:02 -06004023// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
4024// explicitLayout can be kept the same throughout the hierarchical recursive walk.
4025// Mutually recursive with convertGlslangToSpvType().
4026spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
4027 const glslang::TTypeList* glslangMembers,
4028 glslang::TLayoutPacking explicitLayout,
4029 const glslang::TQualifier& qualifier)
4030{
4031 // Create a vector of struct types for SPIR-V to consume
4032 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07004033 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
4034 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004035 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06004036 for (int i = 0; i < (int)glslangMembers->size(); i++) {
4037 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
4038 if (glslangMember.hiddenMember()) {
4039 ++memberDelta;
4040 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08004041 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06004042 } else {
John Kessenich0e737842017-03-24 18:38:16 -06004043 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07004044 if (filterMember(glslangMember)) {
4045 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08004046 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06004047 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07004048 }
Roy05a5b532020-01-03 16:21:34 +08004049 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06004050 }
John Kessenich6090df02016-06-30 21:18:02 -06004051 // modify just this child's view of the qualifier
4052 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4053 InheritQualifiers(memberQualifier, qualifier);
4054
John Kessenich7cdf3fc2017-06-04 13:22:39 -06004055 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06004056 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06004057 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06004058
4059 // recurse
John Kessenichead86222018-03-28 18:01:20 -06004060 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
4061 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004062
4063 // Make forward pointers for any pointer members, and create a list of members to
4064 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06004065 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004066 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
4067 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
4068 }
4069 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004070 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4071 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004072 } else {
4073 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07004074 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
4075 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004076 }
John Kessenich6090df02016-06-30 21:18:02 -06004077 }
4078 }
4079
4080 // Make the SPIR-V type
4081 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06004082 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06004083 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
4084
4085 // Decorate it
4086 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
4087
John Kessenichd72f4882019-01-16 14:55:37 +07004088 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004089 auto it = deferredForwardPointers[i];
4090 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
4091 }
4092
John Kessenich6090df02016-06-30 21:18:02 -06004093 return spvType;
4094}
4095
4096void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
4097 const glslang::TTypeList* glslangMembers,
4098 glslang::TLayoutPacking explicitLayout,
4099 const glslang::TQualifier& qualifier,
4100 spv::Id spvType)
4101{
4102 // Name and decorate the non-hidden members
4103 int offset = -1;
4104 int locationOffset = 0; // for use within the members of this struct
Chow478b2322020-11-04 04:34:19 +08004105 bool memberLocationInvalid = type.isArrayOfArrays() ||
4106 (type.isArray() && (type.getQualifier().isArrayedIo(glslangIntermediate->getStage()) == false));
John Kessenich6090df02016-06-30 21:18:02 -06004107 for (int i = 0; i < (int)glslangMembers->size(); i++) {
4108 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
4109 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06004110 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08004111 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06004112 if (filterMember(glslangMember))
4113 continue;
4114 }
John Kessenich6090df02016-06-30 21:18:02 -06004115
4116 // modify just this child's view of the qualifier
4117 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4118 InheritQualifiers(memberQualifier, qualifier);
4119
4120 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07004121 if (member < 0)
4122 continue;
4123
4124 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
4125 builder.addMemberDecoration(spvType, member,
4126 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
4127 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
4128 // Add interpolation and auxiliary storage decorations only to
4129 // top-level members of Input and Output storage classes
4130 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
4131 type.getQualifier().storage == glslang::EvqVaryingOut) {
4132 if (type.getBasicType() == glslang::EbtBlock ||
4133 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
4134 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
4135 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06004136#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07004137 addMeshNVDecoration(spvType, member, memberQualifier);
4138#endif
John Kessenich6090df02016-06-30 21:18:02 -06004139 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004140 }
4141 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06004142
John Kessenichb9197c82019-08-11 07:41:45 -06004143#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07004144 if (type.getBasicType() == glslang::EbtBlock &&
4145 qualifier.storage == glslang::EvqBuffer) {
4146 // Add memory decorations only to top-level members of shader storage block
4147 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05004148 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07004149 for (unsigned int i = 0; i < memory.size(); ++i)
4150 builder.addMemberDecoration(spvType, member, memory[i]);
4151 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004152
John Kessenichb9197c82019-08-11 07:41:45 -06004153#endif
John Kessenich6090df02016-06-30 21:18:02 -06004154
John Kessenich5d610ee2018-03-07 18:05:55 -07004155 // Location assignment was already completed correctly by the front end,
4156 // just track whether a member needs to be decorated.
4157 // Ignore member locations if the container is an array, as that's
4158 // ill-specified and decisions have been made to not allow this.
Chow478b2322020-11-04 04:34:19 +08004159 if (!memberLocationInvalid && memberQualifier.hasLocation())
John Kessenich5d610ee2018-03-07 18:05:55 -07004160 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004161
John Kessenich5d610ee2018-03-07 18:05:55 -07004162 if (qualifier.hasLocation()) // track for upcoming inheritance
4163 locationOffset += glslangIntermediate->computeTypeLocationSize(
4164 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004165
John Kessenich5d610ee2018-03-07 18:05:55 -07004166 // component, XFB, others
4167 if (glslangMember.getQualifier().hasComponent())
4168 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4169 glslangMember.getQualifier().layoutComponent);
4170 if (glslangMember.getQualifier().hasXfbOffset())
4171 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4172 glslangMember.getQualifier().layoutXfbOffset);
4173 else if (explicitLayout != glslang::ElpNone) {
4174 // figure out what to do with offset, which is accumulating
4175 int nextOffset;
4176 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4177 if (offset >= 0)
4178 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4179 offset = nextOffset;
4180 }
John Kessenich6090df02016-06-30 21:18:02 -06004181
John Kessenich5d610ee2018-03-07 18:05:55 -07004182 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4183 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4184 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004185
John Kessenich5d610ee2018-03-07 18:05:55 -07004186 // built-in variable decorations
4187 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4188 if (builtIn != spv::BuiltInMax)
4189 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004190
John Kessenichb9197c82019-08-11 07:41:45 -06004191#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004192 // nonuniform
4193 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4194
John Kessenichead86222018-03-28 18:01:20 -06004195 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4196 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4197 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4198 memberQualifier.semanticName);
4199 }
4200
John Kessenich5d610ee2018-03-07 18:05:55 -07004201 if (builtIn == spv::BuiltInLayer) {
4202 // SPV_NV_viewport_array2 extension
4203 if (glslangMember.getQualifier().layoutViewportRelative){
4204 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4205 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4206 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004207 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004208 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4209 builder.addMemberDecoration(spvType, member,
4210 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4211 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4212 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4213 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004214 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004215 }
4216 if (glslangMember.getQualifier().layoutPassthrough) {
4217 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4218 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4219 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4220 }
chaoc771d89f2017-01-13 01:10:53 -08004221#endif
John Kessenich6090df02016-06-30 21:18:02 -06004222 }
4223
4224 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004225 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4226 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004227}
4228
John Kessenich6c292d32016-02-15 20:58:50 -07004229// Turn the expression forming the array size into an id.
4230// This is not quite trivial, because of specialization constants.
4231// Sometimes, a raw constant is turned into an Id, and sometimes
4232// a specialization constant expression is.
4233spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4234{
4235 // First, see if this is sized with a node, meaning a specialization constant:
4236 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4237 if (specNode != nullptr) {
4238 builder.clearAccessChain();
4239 specNode->traverse(this);
4240 return accessChainLoad(specNode->getAsTyped()->getType());
4241 }
qining25262b32016-05-06 17:25:16 -04004242
John Kessenich6c292d32016-02-15 20:58:50 -07004243 // Otherwise, need a compile-time (front end) size, get it:
4244 int size = arraySizes.getDimSize(dim);
4245 assert(size > 0);
4246 return builder.makeUintConstant(size);
4247}
4248
John Kessenich103bef92016-02-08 21:38:15 -07004249// Wrap the builder's accessChainLoad to:
4250// - localize handling of RelaxedPrecision
4251// - use the SPIR-V inferred type instead of another conversion of the glslang type
4252// (avoids unnecessary work and possible type punning for structures)
4253// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004254spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4255{
John Kessenich103bef92016-02-08 21:38:15 -07004256 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004257
4258 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4259 coherentFlags |= TranslateCoherent(type);
4260
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004261 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004262 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004263
John Kessenich5611c6d2018-04-05 11:25:02 -06004264 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
greg-lunarg639f5462020-11-12 11:10:07 -07004265 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004266 TranslateNonUniformDecoration(type.getQualifier()),
4267 nominalTypeId,
4268 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4269 TranslateMemoryScope(coherentFlags),
4270 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004271
4272 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004273 if (type.getBasicType() == glslang::EbtBool) {
4274 if (builder.isScalarType(nominalTypeId)) {
4275 // Conversion for bool
4276 spv::Id boolType = builder.makeBoolType();
4277 if (nominalTypeId != boolType)
4278 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4279 } else if (builder.isVectorType(nominalTypeId)) {
4280 // Conversion for bvec
4281 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4282 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4283 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004284 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4285 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004286 }
4287 }
John Kessenich103bef92016-02-08 21:38:15 -07004288
4289 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004290}
4291
Rex Xu27253232016-02-23 17:51:09 +08004292// Wrap the builder's accessChainStore to:
4293// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004294//
4295// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004296void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4297{
4298 // Need to convert to abstract types when necessary
4299 if (type.getBasicType() == glslang::EbtBool) {
4300 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4301
4302 if (builder.isScalarType(nominalTypeId)) {
4303 // Conversion for bool
4304 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004305 if (nominalTypeId != boolType) {
4306 // keep these outside arguments, for determinant order-of-evaluation
4307 spv::Id one = builder.makeUintConstant(1);
4308 spv::Id zero = builder.makeUintConstant(0);
4309 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4310 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004311 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004312 } else if (builder.isVectorType(nominalTypeId)) {
4313 // Conversion for bvec
4314 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4315 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004316 if (nominalTypeId != bvecType) {
4317 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004318 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4319 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4320 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004321 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004322 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4323 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004324 }
4325 }
4326
Jeff Bolz36831c92018-09-05 10:11:41 -05004327 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4328 coherentFlags |= TranslateCoherent(type);
4329
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004330 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004331 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004332
greg-lunarg639f5462020-11-12 11:10:07 -07004333 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004334 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4335 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004336 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004337}
4338
John Kessenich4bf71552016-09-02 11:20:21 -06004339// For storing when types match at the glslang level, but not might match at the
4340// SPIR-V level.
4341//
4342// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004343// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004344// as in a member-decorated way.
4345//
4346// NOTE: This function can handle any store request; if it's not special it
4347// simplifies to a simple OpStore.
4348//
4349// Implicitly uses the existing builder.accessChain as the storage target.
4350void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4351{
John Kessenichb3e24e42016-09-11 12:33:43 -06004352 // we only do the complex path here if it's an aggregate
4353 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004354 accessChainStore(type, rValue);
4355 return;
4356 }
4357
John Kessenichb3e24e42016-09-11 12:33:43 -06004358 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004359 spv::Id rType = builder.getTypeId(rValue);
4360 spv::Id lValue = builder.accessChainGetLValue();
4361 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4362 if (lType == rType) {
4363 accessChainStore(type, rValue);
4364 return;
4365 }
4366
John Kessenichb3e24e42016-09-11 12:33:43 -06004367 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004368 // where the two types were the same type in GLSL. This requires member
4369 // by member copy, recursively.
4370
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004371 // SPIR-V 1.4 added an instruction to do help do this.
4372 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4373 // However, bool in uniform space is changed to int, so
4374 // OpCopyLogical does not work for that.
4375 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4376 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4377 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4378 if (lBool == rBool) {
4379 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4380 accessChainStore(type, logicalCopy);
4381 return;
4382 }
4383 }
4384
John Kessenichb3e24e42016-09-11 12:33:43 -06004385 // If an array, copy element by element.
4386 if (type.isArray()) {
4387 glslang::TType glslangElementType(type, 0);
4388 spv::Id elementRType = builder.getContainedTypeId(rType);
4389 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4390 // get the source member
4391 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004392
John Kessenichb3e24e42016-09-11 12:33:43 -06004393 // set up the target storage
4394 builder.clearAccessChain();
4395 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004396 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4397 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004398
John Kessenichb3e24e42016-09-11 12:33:43 -06004399 // store the member
4400 multiTypeStore(glslangElementType, elementRValue);
4401 }
4402 } else {
4403 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004404
John Kessenichb3e24e42016-09-11 12:33:43 -06004405 // loop over structure members
4406 const glslang::TTypeList& members = *type.getStruct();
4407 for (int m = 0; m < (int)members.size(); ++m) {
4408 const glslang::TType& glslangMemberType = *members[m].type;
4409
4410 // get the source member
4411 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4412 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4413
4414 // set up the target storage
4415 builder.clearAccessChain();
4416 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004417 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4418 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004419
4420 // store the member
4421 multiTypeStore(glslangMemberType, memberRValue);
4422 }
John Kessenich4bf71552016-09-02 11:20:21 -06004423 }
4424}
4425
John Kessenichf85e8062015-12-19 13:57:10 -07004426// Decide whether or not this type should be
4427// decorated with offsets and strides, and if so
4428// whether std140 or std430 rules should be applied.
4429glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004430{
John Kessenichf85e8062015-12-19 13:57:10 -07004431 // has to be a block
4432 if (type.getBasicType() != glslang::EbtBlock)
4433 return glslang::ElpNone;
4434
Chao Chen3c366992018-09-19 11:41:59 -07004435 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004436 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004437 type.getQualifier().storage != glslang::EvqBuffer &&
Caio Marcelo de Oliveira Filho4bfbf622020-06-02 16:58:51 -07004438 type.getQualifier().storage != glslang::EvqShared &&
Chao Chen3c366992018-09-19 11:41:59 -07004439 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004440 return glslang::ElpNone;
4441
4442 // return the layout to use
4443 switch (type.getQualifier().layoutPacking) {
4444 case glslang::ElpStd140:
4445 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004446 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004447 return type.getQualifier().layoutPacking;
4448 default:
4449 return glslang::ElpNone;
4450 }
John Kessenich31ed4832015-09-09 17:51:38 -06004451}
4452
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004453// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004454int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4455 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004456{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004457 int size;
John Kessenich49987892015-12-29 17:11:44 -07004458 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004459 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4460 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004461
4462 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004463}
4464
John Kessenich49987892015-12-29 17:11:44 -07004465// 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 -07004466// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004467int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4468 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004469{
John Kessenich49987892015-12-29 17:11:44 -07004470 glslang::TType elementType;
4471 elementType.shallowCopy(matrixType);
4472 elementType.clearArraySizes();
4473
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004474 int size;
John Kessenich49987892015-12-29 17:11:44 -07004475 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004476 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4477 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004478
4479 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004480}
4481
John Kessenich5e4b1242015-08-06 22:53:06 -06004482// Given a member type of a struct, realign the current offset for it, and compute
4483// the next (not yet aligned) offset for the next member, which will get aligned
4484// on the next call.
4485// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4486// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4487// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004488void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4489 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004490{
4491 // this will get a positive value when deemed necessary
4492 nextOffset = -1;
4493
John Kessenich5e4b1242015-08-06 22:53:06 -06004494 // override anything in currentOffset with user-set offset
4495 if (memberType.getQualifier().hasOffset())
4496 currentOffset = memberType.getQualifier().layoutOffset;
4497
4498 // It could be that current linker usage in glslang updated all the layoutOffset,
4499 // in which case the following code does not matter. But, that's not quite right
4500 // once cross-compilation unit GLSL validation is done, as the original user
4501 // settings are needed in layoutOffset, and then the following will come into play.
4502
John Kessenichf85e8062015-12-19 13:57:10 -07004503 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004504 if (! memberType.getQualifier().hasOffset())
4505 currentOffset = -1;
4506
4507 return;
4508 }
4509
John Kessenichf85e8062015-12-19 13:57:10 -07004510 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004511 if (currentOffset < 0)
4512 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004513
John Kessenich5e4b1242015-08-06 22:53:06 -06004514 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4515 // but possibly not yet correctly aligned.
4516
4517 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004518 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004519 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4520 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004521
4522 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004523 // TODO: make this consistent in early phases of code:
4524 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4525 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4526 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004527 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004528 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004529 int dummySize;
4530 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4531 if (componentAlignment <= 4)
4532 memberAlignment = componentAlignment;
4533 }
4534
4535 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004536 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004537
4538 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004539 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4540 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004541 glslang::RoundToPow2(currentOffset, 16);
4542
John Kessenich5e4b1242015-08-06 22:53:06 -06004543 nextOffset = currentOffset + memberSize;
4544}
4545
David Netoa901ffe2016-06-08 14:11:40 +01004546void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004547{
David Netoa901ffe2016-06-08 14:11:40 +01004548 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4549 switch (glslangBuiltIn)
4550 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004551 case glslang::EbvPointSize:
4552#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004553 case glslang::EbvClipDistance:
4554 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004555 case glslang::EbvViewportMaskNV:
4556 case glslang::EbvSecondaryPositionNV:
4557 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004558 case glslang::EbvPositionPerViewNV:
4559 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004560 case glslang::EbvTaskCountNV:
4561 case glslang::EbvPrimitiveCountNV:
4562 case glslang::EbvPrimitiveIndicesNV:
4563 case glslang::EbvClipDistancePerViewNV:
4564 case glslang::EbvCullDistancePerViewNV:
4565 case glslang::EbvLayerPerViewNV:
4566 case glslang::EbvMeshViewCountNV:
4567 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004568#endif
David Netoa901ffe2016-06-08 14:11:40 +01004569 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4570 // Alternately, we could just call this for any glslang built-in, since the
4571 // capability already guards against duplicates.
4572 TranslateBuiltInDecoration(glslangBuiltIn, false);
4573 break;
4574 default:
4575 // Capabilities were already generated when the struct was declared.
4576 break;
4577 }
John Kessenichebb50532016-05-16 19:22:05 -06004578}
4579
John Kessenich6fccb3c2016-09-19 16:01:41 -06004580bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004581{
John Kessenicheee9d532016-09-19 18:09:30 -06004582 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004583}
4584
John Kessenichd41993d2017-09-10 15:21:05 -06004585// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004586// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4587// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004588bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004589{
John Kessenich6a14f782017-12-04 02:48:10 -07004590 assert(qualifier == glslang::EvqIn ||
4591 qualifier == glslang::EvqOut ||
4592 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004593 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004594 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004595 return qualifier != glslang::EvqConstReadOnly &&
4596 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004597}
4598
4599// Is parameter pass-by-original?
4600bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4601 bool implicitThisParam)
4602{
4603 if (implicitThisParam) // implicit this
4604 return true;
4605 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004606 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004607 return paramType.containsOpaque() || // sampler, etc.
4608 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4609}
4610
John Kessenich140f3df2015-06-26 16:58:36 -06004611// Make all the functions, skeletally, without actually visiting their bodies.
4612void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4613{
John Kessenich8985fc92020-03-03 10:25:07 -07004614 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4615 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004616 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4617 if (paramPrecision != spv::NoPrecision)
4618 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004619 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004620 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004621 // Original and non-writable params pass the pointer directly and
4622 // use restrict/aliased, others are stored to a pointer in Function
4623 // memory and use RestrictPointer/AliasedPointer.
4624 if (originalParam(type.getQualifier().storage, type, false) ||
4625 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004626 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4627 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004628 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004629 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4630 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004631 }
4632 }
John Kessenichfad62972017-07-18 02:35:46 -06004633 };
4634
John Kessenich140f3df2015-06-26 16:58:36 -06004635 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4636 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004637 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004638 continue;
4639
4640 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004641 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004642 //
qining25262b32016-05-06 17:25:16 -04004643 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004644 // function. What it is an address of varies:
4645 //
John Kessenich4bf71552016-09-02 11:20:21 -06004646 // - "in" parameters not marked as "const" can be written to without modifying the calling
4647 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004648 //
4649 // - "const in" parameters can just be the r-value, as no writes need occur.
4650 //
John Kessenich4bf71552016-09-02 11:20:21 -06004651 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4652 // 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 -06004653
4654 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004655 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004656 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4657
John Kessenich155d3512019-08-08 23:29:20 -06004658#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004659 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4660 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004661#else
4662 bool implicitThis = false;
4663#endif
John Kessenich37789792017-03-21 23:56:40 -06004664
John Kessenichfad62972017-07-18 02:35:46 -06004665 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004666 for (int p = 0; p < (int)parameters.size(); ++p) {
4667 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4668 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004669 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004670 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004671 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004672 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4673 else
John Kessenich4bf71552016-09-02 11:20:21 -06004674 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004675 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004676 paramTypes.push_back(typeId);
4677 }
4678
4679 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004680 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4681 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004682 glslFunction->getName().c_str(), paramTypes,
4683 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004684 if (implicitThis)
4685 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004686
4687 // Track function to emit/call later
4688 functionMap[glslFunction->getName().c_str()] = function;
4689
4690 // Set the parameter id's
4691 for (int p = 0; p < (int)parameters.size(); ++p) {
4692 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4693 // give a name too
4694 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004695
4696 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004697 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004698 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004699 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004700 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004701 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004702 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004703 }
4704 }
4705}
4706
4707// Process all the initializers, while skipping the functions and link objects
4708void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4709{
4710 builder.setBuildPoint(shaderEntry->getLastBlock());
4711 for (int i = 0; i < (int)initializers.size(); ++i) {
4712 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004713 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4714 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004715
4716 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004717 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004718 initializer->traverse(this);
4719 }
4720 }
4721}
Daniel Kochffccefd2020-11-23 15:41:27 -05004722// Walk over all linker objects to create a map for payload and callable data linker objects
4723// and their location to be used during codegen for OpTraceKHR and OpExecuteCallableKHR
4724// This is done here since it is possible that these linker objects are not be referenced in the AST
4725void TGlslangToSpvTraverser::collectRayTracingLinkerObjects()
4726{
4727 glslang::TIntermAggregate* linkerObjects = glslangIntermediate->findLinkerObjects();
4728 for (auto& objSeq : linkerObjects->getSequence()) {
4729 auto objNode = objSeq->getAsSymbolNode();
4730 if (objNode != nullptr) {
4731 if (objNode->getQualifier().hasLocation()) {
4732 unsigned int location = objNode->getQualifier().layoutLocation;
4733 auto st = objNode->getQualifier().storage;
4734 int set;
4735 switch (st)
4736 {
4737 case glslang::EvqPayload:
4738 case glslang::EvqPayloadIn:
4739 set = 0;
4740 break;
4741 case glslang::EvqCallableData:
4742 case glslang::EvqCallableDataIn:
4743 set = 1;
4744 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004745
Daniel Kochffccefd2020-11-23 15:41:27 -05004746 default:
4747 set = -1;
4748 }
4749 if (set != -1)
4750 locationToSymbol[set].insert(std::make_pair(location, objNode));
4751 }
4752 }
4753 }
4754}
John Kessenich140f3df2015-06-26 16:58:36 -06004755// Process all the functions, while skipping initializers.
4756void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4757{
4758 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4759 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004760 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004761 node->traverse(this);
4762 }
4763}
4764
4765void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4766{
qining25262b32016-05-06 17:25:16 -04004767 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004768 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004769 currentFunction = functionMap[node->getName().c_str()];
4770 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004771 builder.setBuildPoint(functionBlock);
4772}
4773
John Kessenich8985fc92020-03-03 10:25:07 -07004774void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4775 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004776{
Rex Xufc618912015-09-09 16:42:49 +08004777 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004778
4779 glslang::TSampler sampler = {};
4780 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004781#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004782 bool f16ShadowCompare = false;
4783#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004784 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004785 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4786 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004787#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004788 f16ShadowCompare = sampler.shadow &&
4789 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004790#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004791 }
4792
John Kessenich140f3df2015-06-26 16:58:36 -06004793 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4794 builder.clearAccessChain();
4795 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004796
John Kessenicha28f7a72019-08-06 07:00:58 -06004797#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004798 // Special case l-value operands
4799 bool lvalue = false;
4800 switch (node.getOp()) {
4801 case glslang::EOpImageAtomicAdd:
4802 case glslang::EOpImageAtomicMin:
4803 case glslang::EOpImageAtomicMax:
4804 case glslang::EOpImageAtomicAnd:
4805 case glslang::EOpImageAtomicOr:
4806 case glslang::EOpImageAtomicXor:
4807 case glslang::EOpImageAtomicExchange:
4808 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004809 case glslang::EOpImageAtomicLoad:
4810 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004811 if (i == 0)
4812 lvalue = true;
4813 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004814 case glslang::EOpSparseImageLoad:
4815 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4816 lvalue = true;
4817 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004818 case glslang::EOpSparseTexture:
4819 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4820 lvalue = true;
4821 break;
4822 case glslang::EOpSparseTextureClamp:
4823 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4824 lvalue = true;
4825 break;
4826 case glslang::EOpSparseTextureLod:
4827 case glslang::EOpSparseTextureOffset:
4828 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4829 lvalue = true;
4830 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004831 case glslang::EOpSparseTextureFetch:
4832 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4833 lvalue = true;
4834 break;
4835 case glslang::EOpSparseTextureFetchOffset:
4836 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4837 lvalue = true;
4838 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004839 case glslang::EOpSparseTextureLodOffset:
4840 case glslang::EOpSparseTextureGrad:
4841 case glslang::EOpSparseTextureOffsetClamp:
4842 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4843 lvalue = true;
4844 break;
4845 case glslang::EOpSparseTextureGradOffset:
4846 case glslang::EOpSparseTextureGradClamp:
4847 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4848 lvalue = true;
4849 break;
4850 case glslang::EOpSparseTextureGradOffsetClamp:
4851 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4852 lvalue = true;
4853 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004854 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004855 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4856 lvalue = true;
4857 break;
4858 case glslang::EOpSparseTextureGatherOffset:
4859 case glslang::EOpSparseTextureGatherOffsets:
4860 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4861 lvalue = true;
4862 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004863 case glslang::EOpSparseTextureGatherLod:
4864 if (i == 3)
4865 lvalue = true;
4866 break;
4867 case glslang::EOpSparseTextureGatherLodOffset:
4868 case glslang::EOpSparseTextureGatherLodOffsets:
4869 if (i == 4)
4870 lvalue = true;
4871 break;
Rex Xu129799a2017-07-05 17:23:28 +08004872 case glslang::EOpSparseImageLoadLod:
4873 if (i == 3)
4874 lvalue = true;
4875 break;
Chao Chen3a137962018-09-19 11:41:27 -07004876 case glslang::EOpImageSampleFootprintNV:
4877 if (i == 4)
4878 lvalue = true;
4879 break;
4880 case glslang::EOpImageSampleFootprintClampNV:
4881 case glslang::EOpImageSampleFootprintLodNV:
4882 if (i == 5)
4883 lvalue = true;
4884 break;
4885 case glslang::EOpImageSampleFootprintGradNV:
4886 if (i == 6)
4887 lvalue = true;
4888 break;
4889 case glslang::EOpImageSampleFootprintGradClampNV:
4890 if (i == 7)
4891 lvalue = true;
4892 break;
Rex Xufc618912015-09-09 16:42:49 +08004893 default:
4894 break;
4895 }
4896
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004897 if (lvalue) {
greg-lunarg639f5462020-11-12 11:10:07 -07004898 spv::Id lvalue_id = builder.accessChainGetLValue();
4899 arguments.push_back(lvalue_id);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004900 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
greg-lunarg639f5462020-11-12 11:10:07 -07004901 builder.addDecoration(lvalue_id, TranslateNonUniformDecoration(lvalueCoherentFlags));
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004902 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4903 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004904#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004905 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004906 }
4907}
4908
John Kessenichfc51d282015-08-19 13:34:18 -06004909void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004910{
John Kessenichfc51d282015-08-19 13:34:18 -06004911 builder.clearAccessChain();
4912 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004913 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004914}
John Kessenich140f3df2015-06-26 16:58:36 -06004915
John Kessenichfc51d282015-08-19 13:34:18 -06004916spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4917{
John Kesseniche485c7a2017-05-31 18:50:53 -06004918 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004919 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004920
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004921 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004922
John Kessenichfc51d282015-08-19 13:34:18 -06004923 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004924
John Kessenichf43c7392019-03-31 10:51:57 -06004925 const glslang::TType &imageType = node->getAsAggregate()
4926 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4927 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004928 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004929#ifdef GLSLANG_WEB
4930 const bool f16ShadowCompare = false;
4931#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004932 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004933 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4934 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004935#endif
4936
John Kessenichf43c7392019-03-31 10:51:57 -06004937 const auto signExtensionMask = [&]() {
4938 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4939 if (sampler.type == glslang::EbtUint)
4940 return spv::ImageOperandsZeroExtendMask;
4941 else if (sampler.type == glslang::EbtInt)
4942 return spv::ImageOperandsSignExtendMask;
4943 }
4944 return spv::ImageOperandsMaskNone;
4945 };
4946
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004947 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4948
John Kessenichfc51d282015-08-19 13:34:18 -06004949 std::vector<spv::Id> arguments;
4950 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004951 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004952 else
4953 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004954 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004955
4956 spv::Builder::TextureParameters params = { };
4957 params.sampler = arguments[0];
4958
Rex Xu04db3f52015-09-16 11:44:02 +08004959 glslang::TCrackedTextureOp cracked;
4960 node->crackTexture(sampler, cracked);
4961
amhagan05506bb2017-06-13 16:53:02 -04004962 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004963
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004964 if (builder.isSampledImage(params.sampler) &&
4965 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4966 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4967 if (imageType.getQualifier().isNonUniform()) {
4968 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4969 }
4970 }
John Kessenichfc51d282015-08-19 13:34:18 -06004971 // Check for queries
4972 if (cracked.query) {
4973 switch (node->getOp()) {
4974 case glslang::EOpImageQuerySize:
4975 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004976 if (arguments.size() > 1) {
4977 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004978 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004979 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004980 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004981#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004982 case glslang::EOpImageQuerySamples:
4983 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004984 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004985 case glslang::EOpTextureQueryLod:
4986 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004987 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004988 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004989 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004990 case glslang::EOpSparseTexelsResident:
4991 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004992#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004993 default:
4994 assert(0);
4995 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004996 }
John Kessenich140f3df2015-06-26 16:58:36 -06004997 }
4998
LoopDawg4425f242018-02-18 11:40:01 -07004999 int components = node->getType().getVectorSize();
5000
5001 if (node->getOp() == glslang::EOpTextureFetch) {
5002 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
5003 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
5004 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
5005 // here around e.g. which ones return scalars or other types.
5006 components = 4;
5007 }
5008
5009 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
5010
5011 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
5012
Rex Xufc618912015-09-09 16:42:49 +08005013 // Check for image functions other than queries
5014 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06005015 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06005016 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06005017 spv::IdImmediate image = { true, *(opIt++) };
5018 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07005019
5020 // Handle subpass operations
5021 // TODO: GLSL should change to have the "MS" only on the type rather than the
5022 // built-in function.
5023 if (cracked.subpass) {
5024 // add on the (0,0) coordinate
5025 spv::Id zero = builder.makeIntConstant(0);
5026 std::vector<spv::Id> comps;
5027 comps.push_back(zero);
5028 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06005029 spv::IdImmediate coord = { true,
5030 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
5031 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06005032 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
5033 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005034 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06005035 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
5036 }
5037 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06005038 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005039 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06005040 spv::IdImmediate imageOperand = { true, *(opIt++) };
5041 operands.push_back(imageOperand);
5042 }
John Kessenich6c292d32016-02-15 20:58:50 -07005043 }
John Kessenichfe4e5722017-10-19 02:07:30 -06005044 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
5045 builder.setPrecision(result, precision);
5046 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07005047 }
5048
John Kessenich149afc32018-08-14 13:31:43 -06005049 spv::IdImmediate coord = { true, *(opIt++) };
5050 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08005051 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005052 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005053 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005054 mask = mask | spv::ImageOperandsSampleMask;
5055 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005056 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005057 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5058 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05005059 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07005060 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005061 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5062 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005063 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005064 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005065 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5066 operands.push_back(imageOperands);
5067 }
5068 if (mask & spv::ImageOperandsSampleMask) {
5069 spv::IdImmediate imageOperand = { true, *opIt++ };
5070 operands.push_back(imageOperand);
5071 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005072 if (mask & spv::ImageOperandsLodMask) {
5073 spv::IdImmediate imageOperand = { true, *opIt++ };
5074 operands.push_back(imageOperand);
5075 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005076 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005077 spv::IdImmediate imageOperand = { true,
5078 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005079 operands.push_back(imageOperand);
5080 }
5081
John Kessenich149afc32018-08-14 13:31:43 -06005082 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005083 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06005084
John Kessenich149afc32018-08-14 13:31:43 -06005085 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07005086 builder.setPrecision(result[0], precision);
5087
5088 // If needed, add a conversion constructor to the proper size.
5089 if (components != node->getType().getVectorSize())
5090 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5091
5092 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08005093 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08005094
Jeff Bolz36831c92018-09-05 10:11:41 -05005095 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005096 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06005097 spv::IdImmediate texel = { true, *(opIt + 1) };
5098 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06005099 } else {
5100 spv::IdImmediate texel = { true, *opIt };
5101 operands.push_back(texel);
5102 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005103
5104 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005105 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005106 mask = mask | spv::ImageOperandsSampleMask;
5107 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005108 if (cracked.lod) {
5109 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5110 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5111 mask = mask | spv::ImageOperandsLodMask;
5112 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005113 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5114 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005115 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005116 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005117 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
5118 operands.push_back(imageOperands);
5119 }
5120 if (mask & spv::ImageOperandsSampleMask) {
5121 spv::IdImmediate imageOperand = { true, *opIt++ };
5122 operands.push_back(imageOperand);
5123 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005124 if (mask & spv::ImageOperandsLodMask) {
5125 spv::IdImmediate imageOperand = { true, *opIt++ };
5126 operands.push_back(imageOperand);
5127 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005128 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005129 spv::IdImmediate imageOperand = { true,
5130 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005131 operands.push_back(imageOperand);
5132 }
5133
John Kessenich56bab042015-09-16 10:54:31 -06005134 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06005135 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005136 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06005137 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06005138 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
5139 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08005140 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06005141 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08005142 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
5143
Jeff Bolz36831c92018-09-05 10:11:41 -05005144 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005145 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005146 mask = mask | spv::ImageOperandsSampleMask;
5147 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005148 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005149 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5150 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5151
Jeff Bolz36831c92018-09-05 10:11:41 -05005152 mask = mask | spv::ImageOperandsLodMask;
5153 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005154 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5155 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005156 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005157 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005158 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06005159 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05005160 }
5161 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06005162 spv::IdImmediate imageOperand = { true, *opIt++ };
5163 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05005164 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005165 if (mask & spv::ImageOperandsLodMask) {
5166 spv::IdImmediate imageOperand = { true, *opIt++ };
5167 operands.push_back(imageOperand);
5168 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005169 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07005170 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
5171 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005172 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08005173 }
5174
5175 // Create the return type that was a special structure
5176 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06005177 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08005178 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
5179 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
5180
5181 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
5182
5183 // Decode the return type
5184 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
5185 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07005186 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08005187 // Process image atomic operations
5188
5189 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5190 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005191 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005192 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005193 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005194
Jeff Bolz36831c92018-09-05 10:11:41 -05005195 spv::Id resultTypeId;
5196 // imageAtomicStore has a void return type so base the pointer type on
5197 // the type of the value operand.
5198 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005199 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005200 } else {
5201 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5202 }
John Kessenich56bab042015-09-16 10:54:31 -06005203 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005204 if (imageType.getQualifier().nonUniform) {
5205 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5206 }
Rex Xufc618912015-09-09 16:42:49 +08005207
5208 std::vector<spv::Id> operands;
5209 operands.push_back(pointer);
5210 for (; opIt != arguments.end(); ++opIt)
5211 operands.push_back(*opIt);
5212
John Kessenich8985fc92020-03-03 10:25:07 -07005213 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5214 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005215 }
5216 }
5217
John Kessenicha28f7a72019-08-06 07:00:58 -06005218#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005219 // Check for fragment mask functions other than queries
5220 if (cracked.fragMask) {
5221 assert(sampler.ms);
5222
5223 auto opIt = arguments.begin();
5224 std::vector<spv::Id> operands;
5225
amhagan05506bb2017-06-13 16:53:02 -04005226 operands.push_back(params.sampler);
5227 ++opIt;
5228
5229 if (sampler.isSubpass()) {
5230 // add on the (0,0) coordinate
5231 spv::Id zero = builder.makeIntConstant(0);
5232 std::vector<spv::Id> comps;
5233 comps.push_back(zero);
5234 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005235 operands.push_back(builder.makeCompositeConstant(
5236 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005237 }
5238
5239 for (; opIt != arguments.end(); ++opIt)
5240 operands.push_back(*opIt);
5241
5242 spv::Op fragMaskOp = spv::OpNop;
5243 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5244 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5245 else if (node->getOp() == glslang::EOpFragmentFetch)
5246 fragMaskOp = spv::OpFragmentFetchAMD;
5247
5248 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5249 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5250 return builder.createOp(fragMaskOp, resultType(), operands);
5251 }
5252#endif
5253
Rex Xufc618912015-09-09 16:42:49 +08005254 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005255 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005256 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005257 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005258
John Kessenichfc51d282015-08-19 13:34:18 -06005259 // check for bias argument
5260 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005261 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005262 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005263 if (cracked.gather)
5264 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005265
5266 if (f16ShadowCompare)
5267 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005268 if (cracked.offset)
5269 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005270 else if (cracked.offsets)
5271 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005272 if (cracked.grad)
5273 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005274 if (cracked.lodClamp)
5275 ++nonBiasArgCount;
5276 if (sparse)
5277 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005278 if (imageFootprint)
5279 //Following three extra arguments
5280 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5281 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005282 if ((int)arguments.size() > nonBiasArgCount)
5283 bias = true;
5284 }
5285
John Kessenicha28f7a72019-08-06 07:00:58 -06005286#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005287 if (cracked.gather) {
5288 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5289 if (bias || cracked.lod ||
5290 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5291 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005292 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005293 }
5294 }
5295#endif
5296
John Kessenichfc51d282015-08-19 13:34:18 -06005297 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005298
John Kessenichfc51d282015-08-19 13:34:18 -06005299 params.coords = arguments[1];
5300 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005301 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005302
5303 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005304 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005305 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005306 ++extraArgs;
5307 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005308 params.Dref = arguments[2];
5309 ++extraArgs;
5310 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005311 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005312 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005313 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005314 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005315 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005316 dRefComp = builder.getNumComponents(params.coords) - 1;
5317 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005318 params.Dref = builder.createCompositeExtract(params.coords,
5319 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005320 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005321
5322 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005323 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005324 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005325 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005326 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5327 !(glslangIntermediate->getStage() == EShLangCompute &&
5328 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005329 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5330 noImplicitLod = true;
5331 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005332
5333 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005334 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005335 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005336 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005337 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005338
5339 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005340 if (cracked.grad) {
5341 params.gradX = arguments[2 + extraArgs];
5342 params.gradY = arguments[3 + extraArgs];
5343 extraArgs += 2;
5344 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005345
5346 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005347 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005348 params.offset = arguments[2 + extraArgs];
5349 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005350 } else if (cracked.offsets) {
5351 params.offsets = arguments[2 + extraArgs];
5352 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005353 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005354
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005355#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005356 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005357 if (cracked.lodClamp) {
5358 params.lodClamp = arguments[2 + extraArgs];
5359 ++extraArgs;
5360 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005361 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005362 if (sparse) {
5363 params.texelOut = arguments[2 + extraArgs];
5364 ++extraArgs;
5365 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005366 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005367 if (cracked.gather && ! sampler.shadow) {
5368 // default component is 0, if missing, otherwise an argument
5369 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005370 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005371 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005372 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005373 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005374 }
Chao Chen3a137962018-09-19 11:41:27 -07005375 spv::Id resultStruct = spv::NoResult;
5376 if (imageFootprint) {
5377 //Following three extra arguments
5378 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5379 params.granularity = arguments[2 + extraArgs];
5380 params.coarse = arguments[3 + extraArgs];
5381 resultStruct = arguments[4 + extraArgs];
5382 extraArgs += 3;
5383 }
5384#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005385 // bias
5386 if (bias) {
5387 params.bias = arguments[2 + extraArgs];
5388 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005389 }
John Kessenichfc51d282015-08-19 13:34:18 -06005390
John Kessenicha28f7a72019-08-06 07:00:58 -06005391#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005392 if (imageFootprint) {
5393 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5394 builder.addCapability(spv::CapabilityImageFootprintNV);
5395
5396
5397 //resultStructType(OpenGL type) contains 5 elements:
5398 //struct gl_TextureFootprint2DNV {
5399 // uvec2 anchor;
5400 // uvec2 offset;
5401 // uvec2 mask;
5402 // uint lod;
5403 // uint granularity;
5404 //};
5405 //or
5406 //struct gl_TextureFootprint3DNV {
5407 // uvec3 anchor;
5408 // uvec3 offset;
5409 // uvec2 mask;
5410 // uint lod;
5411 // uint granularity;
5412 //};
5413 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5414 assert(builder.isStructType(resultStructType));
5415
5416 //resType (SPIR-V type) contains 6 elements:
5417 //Member 0 must be a Boolean type scalar(LOD),
5418 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5419 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5420 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5421 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5422 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5423 std::vector<spv::Id> members;
5424 members.push_back(resultType());
5425 for (int i = 0; i < 5; i++) {
5426 members.push_back(builder.getContainedTypeId(resultStructType, i));
5427 }
5428 spv::Id resType = builder.makeStructType(members, "ResType");
5429
5430 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005431 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5432 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005433
5434 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5435 for (int i = 0; i < 5; i++) {
5436 builder.clearAccessChain();
5437 builder.setAccessChainLValue(resultStruct);
5438
5439 //Accessing to a struct we created, no coherent flag is set
5440 spv::Builder::AccessChain::CoherentFlags flags;
5441 flags.clear();
5442
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005443 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005444 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005445 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005446 }
5447 return builder.createCompositeExtract(res, resultType(), 0);
5448 }
5449#endif
5450
John Kessenich65336482016-06-16 14:06:26 -06005451 // projective component (might not to move)
5452 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5453 // are divided by the last component of P."
5454 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5455 // unused components will appear after all used components."
5456 if (cracked.proj) {
5457 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5458 int projTargetComp;
5459 switch (sampler.dim) {
5460 case glslang::Esd1D: projTargetComp = 1; break;
5461 case glslang::Esd2D: projTargetComp = 2; break;
5462 case glslang::EsdRect: projTargetComp = 2; break;
5463 default: projTargetComp = projSourceComp; break;
5464 }
5465 // copy the projective coordinate if we have to
5466 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005467 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005468 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005469 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005470 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005471 }
5472 }
5473
John Kessenichf8d1d742019-10-21 06:55:11 -06005474#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005475 // nonprivate
5476 if (imageType.getQualifier().nonprivate) {
5477 params.nonprivate = true;
5478 }
5479
5480 // volatile
5481 if (imageType.getQualifier().volatil) {
5482 params.volatil = true;
5483 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005484#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005485
St0fFa1184dd2018-04-09 21:08:14 +02005486 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005487 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5488 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005489 );
LoopDawg4425f242018-02-18 11:40:01 -07005490
5491 if (components != node->getType().getVectorSize())
5492 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5493
5494 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005495}
5496
5497spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5498{
5499 // Grab the function's pointer from the previously created function
5500 spv::Function* function = functionMap[node->getName().c_str()];
5501 if (! function)
5502 return 0;
5503
5504 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5505 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5506
5507 // See comments in makeFunctions() for details about the semantics for parameter passing.
5508 //
5509 // These imply we need a four step process:
5510 // 1. Evaluate the arguments
5511 // 2. Allocate and make copies of in, out, and inout arguments
5512 // 3. Make the call
5513 // 4. Copy back the results
5514
John Kessenichd3ed90b2018-05-04 11:43:03 -06005515 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005516 std::vector<spv::Builder::AccessChain> lValues;
5517 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005518 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005519 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005520 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005521 // build l-value
5522 builder.clearAccessChain();
5523 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005524 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005525 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005526 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005527 // save l-value
5528 lValues.push_back(builder.getAccessChain());
5529 } else {
5530 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005531 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005532 }
5533 }
5534
5535 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5536 // copy the original into that space.
5537 //
5538 // Also, build up the list of actual arguments to pass in for the call
5539 int lValueCount = 0;
5540 int rValueCount = 0;
5541 std::vector<spv::Id> spvArgs;
5542 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5543 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005544 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005545 builder.setAccessChain(lValues[lValueCount]);
5546 arg = builder.accessChainGetLValue();
5547 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005548 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005549 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005550 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005551 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005552 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5553 // need to copy the input into output space
5554 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005555 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005556 builder.clearAccessChain();
5557 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005558 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005559 }
5560 ++lValueCount;
5561 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005562 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005563 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005564 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005565 {
John Kessenich435dd802020-06-30 01:27:08 -06005566 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005567 builder.clearAccessChain();
5568 builder.setAccessChainLValue(argCopy);
5569 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005570 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005571 } else
5572 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005573 ++rValueCount;
5574 }
5575 spvArgs.push_back(arg);
5576 }
5577
5578 // 3. Make the call.
5579 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005580 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
greg-lunarg639f5462020-11-12 11:10:07 -07005581 builder.addDecoration(result, TranslateNonUniformDecoration(node->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005582
5583 // 4. Copy back out an "out" arguments.
5584 lValueCount = 0;
5585 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005586 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005587 ++lValueCount;
5588 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005589 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005590 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
greg-lunarg639f5462020-11-12 11:10:07 -07005591 builder.addDecoration(copy, TranslateNonUniformDecoration(argTypes[a]->getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005592 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005593 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005594 }
5595 ++lValueCount;
5596 }
5597 }
5598
5599 return result;
5600}
5601
5602// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005603spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005604 spv::Id typeId, spv::Id left, spv::Id right,
5605 glslang::TBasicType typeProxy, bool reduceComparison)
5606{
John Kessenich66011cb2018-03-06 16:12:04 -07005607 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5608 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005609 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005610
5611 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005612 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005613 bool comparison = false;
5614
5615 switch (op) {
5616 case glslang::EOpAdd:
5617 case glslang::EOpAddAssign:
5618 if (isFloat)
5619 binOp = spv::OpFAdd;
5620 else
5621 binOp = spv::OpIAdd;
5622 break;
5623 case glslang::EOpSub:
5624 case glslang::EOpSubAssign:
5625 if (isFloat)
5626 binOp = spv::OpFSub;
5627 else
5628 binOp = spv::OpISub;
5629 break;
5630 case glslang::EOpMul:
5631 case glslang::EOpMulAssign:
5632 if (isFloat)
5633 binOp = spv::OpFMul;
5634 else
5635 binOp = spv::OpIMul;
5636 break;
5637 case glslang::EOpVectorTimesScalar:
5638 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005639 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005640 if (builder.isVector(right))
5641 std::swap(left, right);
5642 assert(builder.isScalar(right));
5643 needMatchingVectors = false;
5644 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005645 } else if (isFloat)
5646 binOp = spv::OpFMul;
5647 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005648 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005649 break;
5650 case glslang::EOpVectorTimesMatrix:
5651 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005652 binOp = spv::OpVectorTimesMatrix;
5653 break;
5654 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005655 binOp = spv::OpMatrixTimesVector;
5656 break;
5657 case glslang::EOpMatrixTimesScalar:
5658 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005659 binOp = spv::OpMatrixTimesScalar;
5660 break;
5661 case glslang::EOpMatrixTimesMatrix:
5662 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005663 binOp = spv::OpMatrixTimesMatrix;
5664 break;
5665 case glslang::EOpOuterProduct:
5666 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005667 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005668 break;
5669
5670 case glslang::EOpDiv:
5671 case glslang::EOpDivAssign:
5672 if (isFloat)
5673 binOp = spv::OpFDiv;
5674 else if (isUnsigned)
5675 binOp = spv::OpUDiv;
5676 else
5677 binOp = spv::OpSDiv;
5678 break;
5679 case glslang::EOpMod:
5680 case glslang::EOpModAssign:
5681 if (isFloat)
5682 binOp = spv::OpFMod;
5683 else if (isUnsigned)
5684 binOp = spv::OpUMod;
5685 else
5686 binOp = spv::OpSMod;
5687 break;
5688 case glslang::EOpRightShift:
5689 case glslang::EOpRightShiftAssign:
5690 if (isUnsigned)
5691 binOp = spv::OpShiftRightLogical;
5692 else
5693 binOp = spv::OpShiftRightArithmetic;
5694 break;
5695 case glslang::EOpLeftShift:
5696 case glslang::EOpLeftShiftAssign:
5697 binOp = spv::OpShiftLeftLogical;
5698 break;
5699 case glslang::EOpAnd:
5700 case glslang::EOpAndAssign:
5701 binOp = spv::OpBitwiseAnd;
5702 break;
5703 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005704 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005705 binOp = spv::OpLogicalAnd;
5706 break;
5707 case glslang::EOpInclusiveOr:
5708 case glslang::EOpInclusiveOrAssign:
5709 binOp = spv::OpBitwiseOr;
5710 break;
5711 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005712 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005713 binOp = spv::OpLogicalOr;
5714 break;
5715 case glslang::EOpExclusiveOr:
5716 case glslang::EOpExclusiveOrAssign:
5717 binOp = spv::OpBitwiseXor;
5718 break;
5719 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005720 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005721 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005722 break;
5723
Ian Romanickb3bd4022019-01-21 08:57:25 -08005724 case glslang::EOpAbsDifference:
5725 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5726 break;
5727
5728 case glslang::EOpAddSaturate:
5729 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5730 break;
5731
5732 case glslang::EOpSubSaturate:
5733 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5734 break;
5735
5736 case glslang::EOpAverage:
5737 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5738 break;
5739
5740 case glslang::EOpAverageRounded:
5741 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5742 break;
5743
5744 case glslang::EOpMul32x16:
5745 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5746 break;
5747
John Kessenich140f3df2015-06-26 16:58:36 -06005748 case glslang::EOpLessThan:
5749 case glslang::EOpGreaterThan:
5750 case glslang::EOpLessThanEqual:
5751 case glslang::EOpGreaterThanEqual:
5752 case glslang::EOpEqual:
5753 case glslang::EOpNotEqual:
5754 case glslang::EOpVectorEqual:
5755 case glslang::EOpVectorNotEqual:
5756 comparison = true;
5757 break;
5758 default:
5759 break;
5760 }
5761
John Kessenich7c1aa102015-10-15 13:29:11 -06005762 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005763 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005764 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005765 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5766 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005767 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005768
5769 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005770 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005771 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005772
qining25262b32016-05-06 17:25:16 -04005773 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005774 decorations.addNoContraction(builder, result);
5775 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005776 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005777 }
5778
5779 if (! comparison)
5780 return 0;
5781
John Kessenich7c1aa102015-10-15 13:29:11 -06005782 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005783
John Kessenich4583b612016-08-07 19:14:22 -06005784 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005785 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5786 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005787 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005788 return result;
5789 }
John Kessenich140f3df2015-06-26 16:58:36 -06005790
5791 switch (op) {
5792 case glslang::EOpLessThan:
5793 if (isFloat)
5794 binOp = spv::OpFOrdLessThan;
5795 else if (isUnsigned)
5796 binOp = spv::OpULessThan;
5797 else
5798 binOp = spv::OpSLessThan;
5799 break;
5800 case glslang::EOpGreaterThan:
5801 if (isFloat)
5802 binOp = spv::OpFOrdGreaterThan;
5803 else if (isUnsigned)
5804 binOp = spv::OpUGreaterThan;
5805 else
5806 binOp = spv::OpSGreaterThan;
5807 break;
5808 case glslang::EOpLessThanEqual:
5809 if (isFloat)
5810 binOp = spv::OpFOrdLessThanEqual;
5811 else if (isUnsigned)
5812 binOp = spv::OpULessThanEqual;
5813 else
5814 binOp = spv::OpSLessThanEqual;
5815 break;
5816 case glslang::EOpGreaterThanEqual:
5817 if (isFloat)
5818 binOp = spv::OpFOrdGreaterThanEqual;
5819 else if (isUnsigned)
5820 binOp = spv::OpUGreaterThanEqual;
5821 else
5822 binOp = spv::OpSGreaterThanEqual;
5823 break;
5824 case glslang::EOpEqual:
5825 case glslang::EOpVectorEqual:
5826 if (isFloat)
5827 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005828 else if (isBool)
5829 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005830 else
5831 binOp = spv::OpIEqual;
5832 break;
5833 case glslang::EOpNotEqual:
5834 case glslang::EOpVectorNotEqual:
5835 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005836 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005837 else if (isBool)
5838 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005839 else
5840 binOp = spv::OpINotEqual;
5841 break;
5842 default:
5843 break;
5844 }
5845
qining25262b32016-05-06 17:25:16 -04005846 if (binOp != spv::OpNop) {
5847 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005848 decorations.addNoContraction(builder, result);
5849 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005850 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005851 }
John Kessenich140f3df2015-06-26 16:58:36 -06005852
5853 return 0;
5854}
5855
John Kessenich04bb8a02015-12-12 12:28:14 -07005856//
5857// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5858// These can be any of:
5859//
5860// matrix * scalar
5861// scalar * matrix
5862// matrix * matrix linear algebraic
5863// matrix * vector
5864// vector * matrix
5865// matrix * matrix componentwise
5866// matrix op matrix op in {+, -, /}
5867// matrix op scalar op in {+, -, /}
5868// scalar op matrix op in {+, -, /}
5869//
John Kessenichead86222018-03-28 18:01:20 -06005870spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5871 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005872{
5873 bool firstClass = true;
5874
5875 // First, handle first-class matrix operations (* and matrix/scalar)
5876 switch (op) {
5877 case spv::OpFDiv:
5878 if (builder.isMatrix(left) && builder.isScalar(right)) {
5879 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005880 spv::Id resultType = builder.getTypeId(right);
5881 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005882 op = spv::OpMatrixTimesScalar;
5883 } else
5884 firstClass = false;
5885 break;
5886 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005887 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005888 std::swap(left, right);
5889 assert(builder.isScalar(right));
5890 break;
5891 case spv::OpVectorTimesMatrix:
5892 assert(builder.isVector(left));
5893 assert(builder.isMatrix(right));
5894 break;
5895 case spv::OpMatrixTimesVector:
5896 assert(builder.isMatrix(left));
5897 assert(builder.isVector(right));
5898 break;
5899 case spv::OpMatrixTimesMatrix:
5900 assert(builder.isMatrix(left));
5901 assert(builder.isMatrix(right));
5902 break;
5903 default:
5904 firstClass = false;
5905 break;
5906 }
5907
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005908 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5909 firstClass = true;
5910
qining25262b32016-05-06 17:25:16 -04005911 if (firstClass) {
5912 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005913 decorations.addNoContraction(builder, result);
5914 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005915 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005916 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005917
LoopDawg592860c2016-06-09 08:57:35 -06005918 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005919 // The result type of all of them is the same type as the (a) matrix operand.
5920 // The algorithm is to:
5921 // - break the matrix(es) into vectors
5922 // - smear any scalar to a vector
5923 // - do vector operations
5924 // - make a matrix out the vector results
5925 switch (op) {
5926 case spv::OpFAdd:
5927 case spv::OpFSub:
5928 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005929 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005930 case spv::OpFMul:
5931 {
5932 // one time set up...
5933 bool leftMat = builder.isMatrix(left);
5934 bool rightMat = builder.isMatrix(right);
5935 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5936 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5937 spv::Id scalarType = builder.getScalarTypeId(typeId);
5938 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5939 std::vector<spv::Id> results;
5940 spv::Id smearVec = spv::NoResult;
5941 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005942 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005943 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005944 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005945
5946 // do each vector op
5947 for (unsigned int c = 0; c < numCols; ++c) {
5948 std::vector<unsigned int> indexes;
5949 indexes.push_back(c);
5950 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5951 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005952 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005953 decorations.addNoContraction(builder, result);
5954 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005955 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005956 }
5957
5958 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005959 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005960 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005961 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005962 }
5963 default:
5964 assert(0);
5965 return spv::NoResult;
5966 }
5967}
5968
John Kessenichead86222018-03-28 18:01:20 -06005969spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005970 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005971{
5972 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005973 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005974 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005975 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5976 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005977
5978 switch (op) {
5979 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005980 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005981 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005982 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005983 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005984 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005985 unaryOp = spv::OpSNegate;
5986 break;
5987
5988 case glslang::EOpLogicalNot:
5989 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005990 unaryOp = spv::OpLogicalNot;
5991 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005992 case glslang::EOpBitwiseNot:
5993 unaryOp = spv::OpNot;
5994 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005995
John Kessenich140f3df2015-06-26 16:58:36 -06005996 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005997 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005998 break;
5999 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06006000 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06006001 break;
6002 case glslang::EOpTranspose:
6003 unaryOp = spv::OpTranspose;
6004 break;
6005
6006 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06006007 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06006008 break;
6009 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06006010 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06006011 break;
6012 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006013 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06006014 break;
6015 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06006016 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06006017 break;
6018 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006019 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06006020 break;
6021 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06006022 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06006023 break;
6024 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006025 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06006026 break;
6027 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006028 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06006029 break;
6030
6031 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006032 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06006033 break;
6034 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006035 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06006036 break;
6037 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006038 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06006039 break;
6040 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006041 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06006042 break;
6043 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006044 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06006045 break;
6046 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06006047 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06006048 break;
6049
6050 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06006051 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06006052 break;
6053 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06006054 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06006055 break;
6056
6057 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006058 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06006059 break;
6060 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06006061 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06006062 break;
6063 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06006064 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06006065 break;
6066 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06006067 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06006068 break;
6069 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006070 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006071 break;
6072 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06006073 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06006074 break;
6075
6076 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06006077 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06006078 break;
6079 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06006080 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06006081 break;
6082 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06006083 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06006084 break;
6085 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06006086 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06006087 break;
6088 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06006089 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06006090 break;
6091 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006092 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06006093 break;
6094
6095 case glslang::EOpIsNan:
6096 unaryOp = spv::OpIsNan;
6097 break;
6098 case glslang::EOpIsInf:
6099 unaryOp = spv::OpIsInf;
6100 break;
LoopDawg592860c2016-06-09 08:57:35 -06006101 case glslang::EOpIsFinite:
6102 unaryOp = spv::OpIsFinite;
6103 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006104
Rex Xucbc426e2015-12-15 16:03:10 +08006105 case glslang::EOpFloatBitsToInt:
6106 case glslang::EOpFloatBitsToUint:
6107 case glslang::EOpIntBitsToFloat:
6108 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08006109 case glslang::EOpDoubleBitsToInt64:
6110 case glslang::EOpDoubleBitsToUint64:
6111 case glslang::EOpInt64BitsToDouble:
6112 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08006113 case glslang::EOpFloat16BitsToInt16:
6114 case glslang::EOpFloat16BitsToUint16:
6115 case glslang::EOpInt16BitsToFloat16:
6116 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08006117 unaryOp = spv::OpBitcast;
6118 break;
6119
John Kessenich140f3df2015-06-26 16:58:36 -06006120 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006121 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006122 break;
6123 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006124 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006125 break;
6126 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006127 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006128 break;
6129 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006130 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006131 break;
6132 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006133 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006134 break;
6135 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006136 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006137 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006138#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06006139 case glslang::EOpPackSnorm4x8:
6140 libCall = spv::GLSLstd450PackSnorm4x8;
6141 break;
6142 case glslang::EOpUnpackSnorm4x8:
6143 libCall = spv::GLSLstd450UnpackSnorm4x8;
6144 break;
6145 case glslang::EOpPackUnorm4x8:
6146 libCall = spv::GLSLstd450PackUnorm4x8;
6147 break;
6148 case glslang::EOpUnpackUnorm4x8:
6149 libCall = spv::GLSLstd450UnpackUnorm4x8;
6150 break;
6151 case glslang::EOpPackDouble2x32:
6152 libCall = spv::GLSLstd450PackDouble2x32;
6153 break;
6154 case glslang::EOpUnpackDouble2x32:
6155 libCall = spv::GLSLstd450UnpackDouble2x32;
6156 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006157#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006158
Rex Xu8ff43de2016-04-22 16:51:45 +08006159 case glslang::EOpPackInt2x32:
6160 case glslang::EOpUnpackInt2x32:
6161 case glslang::EOpPackUint2x32:
6162 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07006163 case glslang::EOpPack16:
6164 case glslang::EOpPack32:
6165 case glslang::EOpPack64:
6166 case glslang::EOpUnpack32:
6167 case glslang::EOpUnpack16:
6168 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08006169 case glslang::EOpPackInt2x16:
6170 case glslang::EOpUnpackInt2x16:
6171 case glslang::EOpPackUint2x16:
6172 case glslang::EOpUnpackUint2x16:
6173 case glslang::EOpPackInt4x16:
6174 case glslang::EOpUnpackInt4x16:
6175 case glslang::EOpPackUint4x16:
6176 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006177 case glslang::EOpPackFloat2x16:
6178 case glslang::EOpUnpackFloat2x16:
6179 unaryOp = spv::OpBitcast;
6180 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006181
John Kessenich140f3df2015-06-26 16:58:36 -06006182 case glslang::EOpDPdx:
6183 unaryOp = spv::OpDPdx;
6184 break;
6185 case glslang::EOpDPdy:
6186 unaryOp = spv::OpDPdy;
6187 break;
6188 case glslang::EOpFwidth:
6189 unaryOp = spv::OpFwidth;
6190 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006191
John Kessenich140f3df2015-06-26 16:58:36 -06006192 case glslang::EOpAny:
6193 unaryOp = spv::OpAny;
6194 break;
6195 case glslang::EOpAll:
6196 unaryOp = spv::OpAll;
6197 break;
6198
6199 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006200 if (isFloat)
6201 libCall = spv::GLSLstd450FAbs;
6202 else
6203 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006204 break;
6205 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006206 if (isFloat)
6207 libCall = spv::GLSLstd450FSign;
6208 else
6209 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006210 break;
6211
John Kessenicha28f7a72019-08-06 07:00:58 -06006212#ifndef GLSLANG_WEB
6213 case glslang::EOpDPdxFine:
6214 unaryOp = spv::OpDPdxFine;
6215 break;
6216 case glslang::EOpDPdyFine:
6217 unaryOp = spv::OpDPdyFine;
6218 break;
6219 case glslang::EOpFwidthFine:
6220 unaryOp = spv::OpFwidthFine;
6221 break;
6222 case glslang::EOpDPdxCoarse:
6223 unaryOp = spv::OpDPdxCoarse;
6224 break;
6225 case glslang::EOpDPdyCoarse:
6226 unaryOp = spv::OpDPdyCoarse;
6227 break;
6228 case glslang::EOpFwidthCoarse:
6229 unaryOp = spv::OpFwidthCoarse;
6230 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006231 case glslang::EOpRayQueryProceed:
6232 unaryOp = spv::OpRayQueryProceedKHR;
6233 break;
6234 case glslang::EOpRayQueryGetRayTMin:
6235 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6236 break;
6237 case glslang::EOpRayQueryGetRayFlags:
6238 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6239 break;
6240 case glslang::EOpRayQueryGetWorldRayOrigin:
6241 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6242 break;
6243 case glslang::EOpRayQueryGetWorldRayDirection:
6244 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6245 break;
6246 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6247 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6248 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006249 case glslang::EOpInterpolateAtCentroid:
6250 if (typeProxy == glslang::EbtFloat16)
6251 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6252 libCall = spv::GLSLstd450InterpolateAtCentroid;
6253 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006254 case glslang::EOpAtomicCounterIncrement:
6255 case glslang::EOpAtomicCounterDecrement:
6256 case glslang::EOpAtomicCounter:
6257 {
6258 // Handle all of the atomics in one place, in createAtomicOperation()
6259 std::vector<spv::Id> operands;
6260 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006261 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006262 }
6263
John Kessenichfc51d282015-08-19 13:34:18 -06006264 case glslang::EOpBitFieldReverse:
6265 unaryOp = spv::OpBitReverse;
6266 break;
6267 case glslang::EOpBitCount:
6268 unaryOp = spv::OpBitCount;
6269 break;
6270 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006271 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006272 break;
6273 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006274 if (isUnsigned)
6275 libCall = spv::GLSLstd450FindUMsb;
6276 else
6277 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006278 break;
6279
Ian Romanickb3bd4022019-01-21 08:57:25 -08006280 case glslang::EOpCountLeadingZeros:
6281 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6282 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6283 unaryOp = spv::OpUCountLeadingZerosINTEL;
6284 break;
6285
6286 case glslang::EOpCountTrailingZeros:
6287 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6288 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6289 unaryOp = spv::OpUCountTrailingZerosINTEL;
6290 break;
6291
Rex Xu574ab042016-04-14 16:53:07 +08006292 case glslang::EOpBallot:
6293 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006294 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006295 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006296 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006297 case glslang::EOpMinInvocations:
6298 case glslang::EOpMaxInvocations:
6299 case glslang::EOpAddInvocations:
6300 case glslang::EOpMinInvocationsNonUniform:
6301 case glslang::EOpMaxInvocationsNonUniform:
6302 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006303 case glslang::EOpMinInvocationsInclusiveScan:
6304 case glslang::EOpMaxInvocationsInclusiveScan:
6305 case glslang::EOpAddInvocationsInclusiveScan:
6306 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6307 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6308 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6309 case glslang::EOpMinInvocationsExclusiveScan:
6310 case glslang::EOpMaxInvocationsExclusiveScan:
6311 case glslang::EOpAddInvocationsExclusiveScan:
6312 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6313 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6314 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006315 {
6316 std::vector<spv::Id> operands;
6317 operands.push_back(operand);
6318 return createInvocationsOperation(op, typeId, operands, typeProxy);
6319 }
John Kessenich66011cb2018-03-06 16:12:04 -07006320 case glslang::EOpSubgroupAll:
6321 case glslang::EOpSubgroupAny:
6322 case glslang::EOpSubgroupAllEqual:
6323 case glslang::EOpSubgroupBroadcastFirst:
6324 case glslang::EOpSubgroupBallot:
6325 case glslang::EOpSubgroupInverseBallot:
6326 case glslang::EOpSubgroupBallotBitCount:
6327 case glslang::EOpSubgroupBallotInclusiveBitCount:
6328 case glslang::EOpSubgroupBallotExclusiveBitCount:
6329 case glslang::EOpSubgroupBallotFindLSB:
6330 case glslang::EOpSubgroupBallotFindMSB:
6331 case glslang::EOpSubgroupAdd:
6332 case glslang::EOpSubgroupMul:
6333 case glslang::EOpSubgroupMin:
6334 case glslang::EOpSubgroupMax:
6335 case glslang::EOpSubgroupAnd:
6336 case glslang::EOpSubgroupOr:
6337 case glslang::EOpSubgroupXor:
6338 case glslang::EOpSubgroupInclusiveAdd:
6339 case glslang::EOpSubgroupInclusiveMul:
6340 case glslang::EOpSubgroupInclusiveMin:
6341 case glslang::EOpSubgroupInclusiveMax:
6342 case glslang::EOpSubgroupInclusiveAnd:
6343 case glslang::EOpSubgroupInclusiveOr:
6344 case glslang::EOpSubgroupInclusiveXor:
6345 case glslang::EOpSubgroupExclusiveAdd:
6346 case glslang::EOpSubgroupExclusiveMul:
6347 case glslang::EOpSubgroupExclusiveMin:
6348 case glslang::EOpSubgroupExclusiveMax:
6349 case glslang::EOpSubgroupExclusiveAnd:
6350 case glslang::EOpSubgroupExclusiveOr:
6351 case glslang::EOpSubgroupExclusiveXor:
6352 case glslang::EOpSubgroupQuadSwapHorizontal:
6353 case glslang::EOpSubgroupQuadSwapVertical:
6354 case glslang::EOpSubgroupQuadSwapDiagonal: {
6355 std::vector<spv::Id> operands;
6356 operands.push_back(operand);
6357 return createSubgroupOperation(op, typeId, operands, typeProxy);
6358 }
Rex Xu9d93a232016-05-05 12:30:44 +08006359 case glslang::EOpMbcnt:
6360 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6361 libCall = spv::MbcntAMD;
6362 break;
6363
6364 case glslang::EOpCubeFaceIndex:
6365 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6366 libCall = spv::CubeFaceIndexAMD;
6367 break;
6368
6369 case glslang::EOpCubeFaceCoord:
6370 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6371 libCall = spv::CubeFaceCoordAMD;
6372 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006373 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006374 unaryOp = spv::OpGroupNonUniformPartitionNV;
6375 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006376 case glslang::EOpConstructReference:
6377 unaryOp = spv::OpBitcast;
6378 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05006379
6380 case glslang::EOpConvUint64ToAccStruct:
6381 case glslang::EOpConvUvec2ToAccStruct:
6382 unaryOp = spv::OpConvertUToAccelerationStructureKHR;
6383 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006384#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006385
6386 case glslang::EOpCopyObject:
6387 unaryOp = spv::OpCopyObject;
6388 break;
6389
John Kessenich140f3df2015-06-26 16:58:36 -06006390 default:
6391 return 0;
6392 }
6393
6394 spv::Id id;
6395 if (libCall >= 0) {
6396 std::vector<spv::Id> args;
6397 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006398 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006399 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006400 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006401 }
John Kessenich140f3df2015-06-26 16:58:36 -06006402
John Kessenichb9197c82019-08-11 07:41:45 -06006403 decorations.addNoContraction(builder, id);
6404 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006405 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006406}
6407
John Kessenich7a53f762016-01-20 11:19:27 -07006408// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006409spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6410 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006411{
6412 // Handle unary operations vector by vector.
6413 // The result type is the same type as the original type.
6414 // The algorithm is to:
6415 // - break the matrix into vectors
6416 // - apply the operation to each vector
6417 // - make a matrix out the vector results
6418
6419 // get the types sorted out
6420 int numCols = builder.getNumColumns(operand);
6421 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006422 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6423 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006424 std::vector<spv::Id> results;
6425
6426 // do each vector op
6427 for (int c = 0; c < numCols; ++c) {
6428 std::vector<unsigned int> indexes;
6429 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006430 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6431 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006432 decorations.addNoContraction(builder, destVec);
6433 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006434 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006435 }
6436
6437 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006438 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006439 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006440 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006441}
6442
John Kessenichad7645f2018-06-04 19:11:25 -06006443// For converting integers where both the bitwidth and the signedness could
6444// change, but only do the width change here. The caller is still responsible
6445// for the signedness conversion.
6446spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006447{
John Kessenichad7645f2018-06-04 19:11:25 -06006448 // Get the result type width, based on the type to convert to.
6449 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006450 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006451 case glslang::EOpConvInt16ToUint8:
6452 case glslang::EOpConvIntToUint8:
6453 case glslang::EOpConvInt64ToUint8:
6454 case glslang::EOpConvUint16ToInt8:
6455 case glslang::EOpConvUintToInt8:
6456 case glslang::EOpConvUint64ToInt8:
6457 width = 8;
6458 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006459 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006460 case glslang::EOpConvIntToUint16:
6461 case glslang::EOpConvInt64ToUint16:
6462 case glslang::EOpConvUint8ToInt16:
6463 case glslang::EOpConvUintToInt16:
6464 case glslang::EOpConvUint64ToInt16:
6465 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006466 break;
6467 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006468 case glslang::EOpConvInt16ToUint:
6469 case glslang::EOpConvInt64ToUint:
6470 case glslang::EOpConvUint8ToInt:
6471 case glslang::EOpConvUint16ToInt:
6472 case glslang::EOpConvUint64ToInt:
6473 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006474 break;
6475 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006476 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006477 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006478 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006479 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006480 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006481 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006482 break;
6483
6484 default:
6485 assert(false && "Default missing");
6486 break;
6487 }
6488
John Kessenichad7645f2018-06-04 19:11:25 -06006489 // Get the conversion operation and result type,
6490 // based on the target width, but the source type.
6491 spv::Id type = spv::NoType;
6492 spv::Op convOp = spv::OpNop;
6493 switch(op) {
6494 case glslang::EOpConvInt8ToUint16:
6495 case glslang::EOpConvInt8ToUint:
6496 case glslang::EOpConvInt8ToUint64:
6497 case glslang::EOpConvInt16ToUint8:
6498 case glslang::EOpConvInt16ToUint:
6499 case glslang::EOpConvInt16ToUint64:
6500 case glslang::EOpConvIntToUint8:
6501 case glslang::EOpConvIntToUint16:
6502 case glslang::EOpConvIntToUint64:
6503 case glslang::EOpConvInt64ToUint8:
6504 case glslang::EOpConvInt64ToUint16:
6505 case glslang::EOpConvInt64ToUint:
6506 convOp = spv::OpSConvert;
6507 type = builder.makeIntType(width);
6508 break;
6509 default:
6510 convOp = spv::OpUConvert;
6511 type = builder.makeUintType(width);
6512 break;
6513 }
6514
John Kessenich66011cb2018-03-06 16:12:04 -07006515 if (vectorSize > 0)
6516 type = builder.makeVectorType(type, vectorSize);
6517
John Kessenichad7645f2018-06-04 19:11:25 -06006518 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006519}
6520
John Kessenichead86222018-03-28 18:01:20 -06006521spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6522 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006523{
6524 spv::Op convOp = spv::OpNop;
6525 spv::Id zero = 0;
6526 spv::Id one = 0;
6527
6528 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6529
6530 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006531 case glslang::EOpConvIntToBool:
6532 case glslang::EOpConvUintToBool:
6533 zero = builder.makeUintConstant(0);
6534 zero = makeSmearedConstant(zero, vectorSize);
6535 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006536 case glslang::EOpConvFloatToBool:
6537 zero = builder.makeFloatConstant(0.0F);
6538 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006539 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006540 case glslang::EOpConvBoolToFloat:
6541 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006542 zero = builder.makeFloatConstant(0.0F);
6543 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006544 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006545
John Kessenich140f3df2015-06-26 16:58:36 -06006546 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006547 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006548#ifndef GLSLANG_WEB
6549 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006550 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006551 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006552 } else
6553#endif
6554 {
6555 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006556 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006557 }
Rex Xucabbb782017-03-24 13:41:14 +08006558
John Kessenich140f3df2015-06-26 16:58:36 -06006559 convOp = spv::OpSelect;
6560 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006561
John Kessenich140f3df2015-06-26 16:58:36 -06006562 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006563 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006564#ifndef GLSLANG_WEB
6565 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006566 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006567 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006568 } else
6569#endif
6570 {
6571 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006572 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006573 }
Rex Xucabbb782017-03-24 13:41:14 +08006574
John Kessenich140f3df2015-06-26 16:58:36 -06006575 convOp = spv::OpSelect;
6576 break;
6577
John Kessenich66011cb2018-03-06 16:12:04 -07006578 case glslang::EOpConvInt8ToFloat16:
6579 case glslang::EOpConvInt8ToFloat:
6580 case glslang::EOpConvInt8ToDouble:
6581 case glslang::EOpConvInt16ToFloat16:
6582 case glslang::EOpConvInt16ToFloat:
6583 case glslang::EOpConvInt16ToDouble:
6584 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006585 case glslang::EOpConvIntToFloat:
6586 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006587 case glslang::EOpConvInt64ToFloat:
6588 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006589 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006590 convOp = spv::OpConvertSToF;
6591 break;
6592
John Kessenich66011cb2018-03-06 16:12:04 -07006593 case glslang::EOpConvUint8ToFloat16:
6594 case glslang::EOpConvUint8ToFloat:
6595 case glslang::EOpConvUint8ToDouble:
6596 case glslang::EOpConvUint16ToFloat16:
6597 case glslang::EOpConvUint16ToFloat:
6598 case glslang::EOpConvUint16ToDouble:
6599 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006600 case glslang::EOpConvUintToFloat:
6601 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006602 case glslang::EOpConvUint64ToFloat:
6603 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006604 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006605 convOp = spv::OpConvertUToF;
6606 break;
6607
John Kessenich66011cb2018-03-06 16:12:04 -07006608 case glslang::EOpConvFloat16ToInt8:
6609 case glslang::EOpConvFloatToInt8:
6610 case glslang::EOpConvDoubleToInt8:
6611 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006612 case glslang::EOpConvFloatToInt16:
6613 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006614 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006615 case glslang::EOpConvFloatToInt:
6616 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006617 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006618 case glslang::EOpConvFloatToInt64:
6619 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006620 convOp = spv::OpConvertFToS;
6621 break;
6622
John Kessenich66011cb2018-03-06 16:12:04 -07006623 case glslang::EOpConvUint8ToInt8:
6624 case glslang::EOpConvInt8ToUint8:
6625 case glslang::EOpConvUint16ToInt16:
6626 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006627 case glslang::EOpConvUintToInt:
6628 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006629 case glslang::EOpConvUint64ToInt64:
6630 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006631 if (builder.isInSpecConstCodeGenMode()) {
6632 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006633#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006634 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6635 zero = builder.makeUint8Constant(0);
6636 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006637 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006638 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6639 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006640 } else
6641#endif
6642 {
Rex Xucabbb782017-03-24 13:41:14 +08006643 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006644 }
qining189b2032016-04-12 23:16:20 -04006645 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006646 // Use OpIAdd, instead of OpBitcast to do the conversion when
6647 // generating for OpSpecConstantOp instruction.
6648 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6649 }
6650 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006651 convOp = spv::OpBitcast;
6652 break;
6653
John Kessenich66011cb2018-03-06 16:12:04 -07006654 case glslang::EOpConvFloat16ToUint8:
6655 case glslang::EOpConvFloatToUint8:
6656 case glslang::EOpConvDoubleToUint8:
6657 case glslang::EOpConvFloat16ToUint16:
6658 case glslang::EOpConvFloatToUint16:
6659 case glslang::EOpConvDoubleToUint16:
6660 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006661 case glslang::EOpConvFloatToUint:
6662 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006663 case glslang::EOpConvFloatToUint64:
6664 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006665 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006666 convOp = spv::OpConvertFToU;
6667 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006668
John Kessenich39697cd2019-08-08 10:35:51 -06006669#ifndef GLSLANG_WEB
6670 case glslang::EOpConvInt8ToBool:
6671 case glslang::EOpConvUint8ToBool:
6672 zero = builder.makeUint8Constant(0);
6673 zero = makeSmearedConstant(zero, vectorSize);
6674 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6675 case glslang::EOpConvInt16ToBool:
6676 case glslang::EOpConvUint16ToBool:
6677 zero = builder.makeUint16Constant(0);
6678 zero = makeSmearedConstant(zero, vectorSize);
6679 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6680 case glslang::EOpConvInt64ToBool:
6681 case glslang::EOpConvUint64ToBool:
6682 zero = builder.makeUint64Constant(0);
6683 zero = makeSmearedConstant(zero, vectorSize);
6684 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6685 case glslang::EOpConvDoubleToBool:
6686 zero = builder.makeDoubleConstant(0.0);
6687 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006688 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006689 case glslang::EOpConvFloat16ToBool:
6690 zero = builder.makeFloat16Constant(0.0F);
6691 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006692 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006693 case glslang::EOpConvBoolToDouble:
6694 convOp = spv::OpSelect;
6695 zero = builder.makeDoubleConstant(0.0);
6696 one = builder.makeDoubleConstant(1.0);
6697 break;
6698 case glslang::EOpConvBoolToFloat16:
6699 convOp = spv::OpSelect;
6700 zero = builder.makeFloat16Constant(0.0F);
6701 one = builder.makeFloat16Constant(1.0F);
6702 break;
6703 case glslang::EOpConvBoolToInt8:
6704 zero = builder.makeInt8Constant(0);
6705 one = builder.makeInt8Constant(1);
6706 convOp = spv::OpSelect;
6707 break;
6708 case glslang::EOpConvBoolToUint8:
6709 zero = builder.makeUint8Constant(0);
6710 one = builder.makeUint8Constant(1);
6711 convOp = spv::OpSelect;
6712 break;
6713 case glslang::EOpConvBoolToInt16:
6714 zero = builder.makeInt16Constant(0);
6715 one = builder.makeInt16Constant(1);
6716 convOp = spv::OpSelect;
6717 break;
6718 case glslang::EOpConvBoolToUint16:
6719 zero = builder.makeUint16Constant(0);
6720 one = builder.makeUint16Constant(1);
6721 convOp = spv::OpSelect;
6722 break;
6723 case glslang::EOpConvDoubleToFloat:
6724 case glslang::EOpConvFloatToDouble:
6725 case glslang::EOpConvDoubleToFloat16:
6726 case glslang::EOpConvFloat16ToDouble:
6727 case glslang::EOpConvFloatToFloat16:
6728 case glslang::EOpConvFloat16ToFloat:
6729 convOp = spv::OpFConvert;
6730 if (builder.isMatrixType(destType))
6731 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6732 break;
6733
John Kessenich66011cb2018-03-06 16:12:04 -07006734 case glslang::EOpConvInt8ToInt16:
6735 case glslang::EOpConvInt8ToInt:
6736 case glslang::EOpConvInt8ToInt64:
6737 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006738 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006739 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006740 case glslang::EOpConvIntToInt8:
6741 case glslang::EOpConvIntToInt16:
6742 case glslang::EOpConvIntToInt64:
6743 case glslang::EOpConvInt64ToInt8:
6744 case glslang::EOpConvInt64ToInt16:
6745 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006746 convOp = spv::OpSConvert;
6747 break;
6748
John Kessenich66011cb2018-03-06 16:12:04 -07006749 case glslang::EOpConvUint8ToUint16:
6750 case glslang::EOpConvUint8ToUint:
6751 case glslang::EOpConvUint8ToUint64:
6752 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006753 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006754 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006755 case glslang::EOpConvUintToUint8:
6756 case glslang::EOpConvUintToUint16:
6757 case glslang::EOpConvUintToUint64:
6758 case glslang::EOpConvUint64ToUint8:
6759 case glslang::EOpConvUint64ToUint16:
6760 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006761 convOp = spv::OpUConvert;
6762 break;
6763
John Kessenich66011cb2018-03-06 16:12:04 -07006764 case glslang::EOpConvInt8ToUint16:
6765 case glslang::EOpConvInt8ToUint:
6766 case glslang::EOpConvInt8ToUint64:
6767 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006768 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006769 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006770 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006771 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006772 case glslang::EOpConvIntToUint64:
6773 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006774 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006775 case glslang::EOpConvInt64ToUint:
6776 case glslang::EOpConvUint8ToInt16:
6777 case glslang::EOpConvUint8ToInt:
6778 case glslang::EOpConvUint8ToInt64:
6779 case glslang::EOpConvUint16ToInt8:
6780 case glslang::EOpConvUint16ToInt:
6781 case glslang::EOpConvUint16ToInt64:
6782 case glslang::EOpConvUintToInt8:
6783 case glslang::EOpConvUintToInt16:
6784 case glslang::EOpConvUintToInt64:
6785 case glslang::EOpConvUint64ToInt8:
6786 case glslang::EOpConvUint64ToInt16:
6787 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006788 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006789 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006790
6791 if (builder.isInSpecConstCodeGenMode()) {
6792 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006793 switch(op) {
6794 case glslang::EOpConvInt16ToUint8:
6795 case glslang::EOpConvIntToUint8:
6796 case glslang::EOpConvInt64ToUint8:
6797 case glslang::EOpConvUint16ToInt8:
6798 case glslang::EOpConvUintToInt8:
6799 case glslang::EOpConvUint64ToInt8:
6800 zero = builder.makeUint8Constant(0);
6801 break;
6802 case glslang::EOpConvInt8ToUint16:
6803 case glslang::EOpConvIntToUint16:
6804 case glslang::EOpConvInt64ToUint16:
6805 case glslang::EOpConvUint8ToInt16:
6806 case glslang::EOpConvUintToInt16:
6807 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006808 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006809 break;
6810 case glslang::EOpConvInt8ToUint:
6811 case glslang::EOpConvInt16ToUint:
6812 case glslang::EOpConvInt64ToUint:
6813 case glslang::EOpConvUint8ToInt:
6814 case glslang::EOpConvUint16ToInt:
6815 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006816 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006817 break;
6818 case glslang::EOpConvInt8ToUint64:
6819 case glslang::EOpConvInt16ToUint64:
6820 case glslang::EOpConvIntToUint64:
6821 case glslang::EOpConvUint8ToInt64:
6822 case glslang::EOpConvUint16ToInt64:
6823 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006824 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006825 break;
6826 default:
6827 assert(false && "Default missing");
6828 break;
6829 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006830 zero = makeSmearedConstant(zero, vectorSize);
6831 // Use OpIAdd, instead of OpBitcast to do the conversion when
6832 // generating for OpSpecConstantOp instruction.
6833 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6834 }
6835 // For normal run-time conversion instruction, use OpBitcast.
6836 convOp = spv::OpBitcast;
6837 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006838 case glslang::EOpConvUint64ToPtr:
6839 convOp = spv::OpConvertUToPtr;
6840 break;
6841 case glslang::EOpConvPtrToUint64:
6842 convOp = spv::OpConvertPtrToU;
6843 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006844 case glslang::EOpConvPtrToUvec2:
6845 case glslang::EOpConvUvec2ToPtr:
6846 convOp = spv::OpBitcast;
6847 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006848#endif
6849
John Kessenich140f3df2015-06-26 16:58:36 -06006850 default:
6851 break;
6852 }
6853
6854 spv::Id result = 0;
6855 if (convOp == spv::OpNop)
6856 return result;
6857
6858 if (convOp == spv::OpSelect) {
6859 zero = makeSmearedConstant(zero, vectorSize);
6860 one = makeSmearedConstant(one, vectorSize);
6861 result = builder.createTriOp(convOp, destType, operand, one, zero);
6862 } else
6863 result = builder.createUnaryOp(convOp, destType, operand);
6864
John Kessenichead86222018-03-28 18:01:20 -06006865 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006866 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006867 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006868}
6869
6870spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6871{
6872 if (vectorSize == 0)
6873 return constant;
6874
6875 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6876 std::vector<spv::Id> components;
6877 for (int c = 0; c < vectorSize; ++c)
6878 components.push_back(constant);
6879 return builder.makeCompositeConstant(vectorTypeId, components);
6880}
6881
John Kessenich426394d2015-07-23 10:22:48 -06006882// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006883spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6884 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6885 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006886{
6887 spv::Op opCode = spv::OpNop;
6888
6889 switch (op) {
6890 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006891 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006892 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006893 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006894 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6895 opCode = spv::OpAtomicFAddEXT;
6896 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6897 if (typeProxy == glslang::EbtFloat)
6898 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6899 else
6900 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6901 }
John Kessenich426394d2015-07-23 10:22:48 -06006902 break;
greg-lunarg4e064ee2021-03-15 11:26:11 -06006903 case glslang::EOpAtomicSubtract:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006904 case glslang::EOpAtomicCounterSubtract:
6905 opCode = spv::OpAtomicISub;
6906 break;
John Kessenich426394d2015-07-23 10:22:48 -06006907 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006908 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006909 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006910 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6911 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006912 break;
6913 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006914 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006915 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006916 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6917 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006918 break;
6919 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006920 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006921 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006922 opCode = spv::OpAtomicAnd;
6923 break;
6924 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006925 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006926 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006927 opCode = spv::OpAtomicOr;
6928 break;
6929 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006930 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006931 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006932 opCode = spv::OpAtomicXor;
6933 break;
6934 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006935 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006936 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006937 opCode = spv::OpAtomicExchange;
6938 break;
6939 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006940 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006941 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006942 opCode = spv::OpAtomicCompareExchange;
6943 break;
6944 case glslang::EOpAtomicCounterIncrement:
6945 opCode = spv::OpAtomicIIncrement;
6946 break;
6947 case glslang::EOpAtomicCounterDecrement:
6948 opCode = spv::OpAtomicIDecrement;
6949 break;
6950 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006951 case glslang::EOpImageAtomicLoad:
6952 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006953 opCode = spv::OpAtomicLoad;
6954 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006955 case glslang::EOpAtomicStore:
6956 case glslang::EOpImageAtomicStore:
6957 opCode = spv::OpAtomicStore;
6958 break;
John Kessenich426394d2015-07-23 10:22:48 -06006959 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006960 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006961 break;
6962 }
6963
Rex Xue8fe8b02017-09-26 15:42:56 +08006964 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6965 builder.addCapability(spv::CapabilityInt64Atomics);
6966
John Kessenich426394d2015-07-23 10:22:48 -06006967 // Sort out the operands
6968 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006969 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006970 // - compare-exchange swaps the value and comparator
6971 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006972 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006973 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6974 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6975 spv::Id scopeId;
6976 if (glslangIntermediate->usingVulkanMemoryModel()) {
6977 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6978 } else {
6979 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6980 }
6981 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006982 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6983 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006984 spv::MemorySemanticsVolatileMask :
6985 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006986 spv::Id semanticsId2 = semanticsId;
6987
6988 pointerId = operands[0];
6989 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6990 // no additional operands
6991 } else if (opCode == spv::OpAtomicCompareExchange) {
6992 compareId = operands[1];
6993 valueId = operands[2];
6994 if (operands.size() > 3) {
6995 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006996 semanticsId = builder.makeUintConstant(
6997 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6998 semanticsId2 = builder.makeUintConstant(
6999 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05007000 }
7001 } else if (opCode == spv::OpAtomicLoad) {
7002 if (operands.size() > 1) {
7003 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07007004 semanticsId = builder.makeUintConstant(
7005 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05007006 }
7007 } else {
7008 // atomic store or RMW
7009 valueId = operands[1];
7010 if (operands.size() > 2) {
7011 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07007012 semanticsId = builder.makeUintConstant
7013 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05007014 }
Rex Xu04db3f52015-09-16 11:44:02 +08007015 }
John Kessenich426394d2015-07-23 10:22:48 -06007016
Jeff Bolz36831c92018-09-05 10:11:41 -05007017 // Check for capabilities
7018 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007019 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
7020 spv::MemorySemanticsMakeVisibleKHRMask |
7021 spv::MemorySemanticsOutputMemoryKHRMask |
7022 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007023 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7024 }
John Kessenich426394d2015-07-23 10:22:48 -06007025
Jeff Bolzbfd84a32021-01-27 13:14:34 -06007026 if (builder.getConstantScalar(scopeId) == spv::ScopeQueueFamily) {
7027 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7028 }
7029
Jeff Bolz36831c92018-09-05 10:11:41 -05007030 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
7031 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7032 }
John Kessenich48d6e792017-10-06 21:21:48 -06007033
Jeff Bolz36831c92018-09-05 10:11:41 -05007034 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
7035 spvAtomicOperands.push_back(pointerId);
7036 spvAtomicOperands.push_back(scopeId);
7037 spvAtomicOperands.push_back(semanticsId);
7038 if (opCode == spv::OpAtomicCompareExchange) {
7039 spvAtomicOperands.push_back(semanticsId2);
7040 spvAtomicOperands.push_back(valueId);
7041 spvAtomicOperands.push_back(compareId);
7042 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
7043 spvAtomicOperands.push_back(valueId);
7044 }
John Kessenich48d6e792017-10-06 21:21:48 -06007045
Jeff Bolz36831c92018-09-05 10:11:41 -05007046 if (opCode == spv::OpAtomicStore) {
7047 builder.createNoResultOp(opCode, spvAtomicOperands);
7048 return 0;
7049 } else {
7050 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
7051
7052 // GLSL and HLSL atomic-counter decrement return post-decrement value,
7053 // while SPIR-V returns pre-decrement value. Translate between these semantics.
7054 if (op == glslang::EOpAtomicCounterDecrement)
7055 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
7056
7057 return resultId;
7058 }
John Kessenich426394d2015-07-23 10:22:48 -06007059}
7060
John Kessenich91cef522016-05-05 16:45:40 -06007061// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07007062spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
7063 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06007064{
John Kessenich66011cb2018-03-06 16:12:04 -07007065 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7066 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08007067
Rex Xu51596642016-09-21 18:56:12 +08007068 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06007069 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08007070 spv::GroupOperation groupOperation = spv::GroupOperationMax;
7071
chaocf200da82016-12-20 12:44:35 -08007072 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
7073 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08007074 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
7075 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007076 } else if (op == glslang::EOpAnyInvocation ||
7077 op == glslang::EOpAllInvocations ||
7078 op == glslang::EOpAllInvocationsEqual) {
7079 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
7080 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08007081 } else {
7082 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08007083 if (op == glslang::EOpMinInvocationsNonUniform ||
7084 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08007085 op == glslang::EOpAddInvocationsNonUniform ||
7086 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7087 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7088 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
7089 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
7090 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
7091 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08007092 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08007093
Rex Xu430ef402016-10-14 17:22:23 +08007094 switch (op) {
7095 case glslang::EOpMinInvocations:
7096 case glslang::EOpMaxInvocations:
7097 case glslang::EOpAddInvocations:
7098 case glslang::EOpMinInvocationsNonUniform:
7099 case glslang::EOpMaxInvocationsNonUniform:
7100 case glslang::EOpAddInvocationsNonUniform:
7101 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08007102 break;
7103 case glslang::EOpMinInvocationsInclusiveScan:
7104 case glslang::EOpMaxInvocationsInclusiveScan:
7105 case glslang::EOpAddInvocationsInclusiveScan:
7106 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7107 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7108 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7109 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007110 break;
7111 case glslang::EOpMinInvocationsExclusiveScan:
7112 case glslang::EOpMaxInvocationsExclusiveScan:
7113 case glslang::EOpAddInvocationsExclusiveScan:
7114 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7115 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7116 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7117 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08007118 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07007119 default:
7120 break;
Rex Xu430ef402016-10-14 17:22:23 +08007121 }
John Kessenich149afc32018-08-14 13:31:43 -06007122 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7123 spvGroupOperands.push_back(scope);
7124 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007125 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007126 spvGroupOperands.push_back(groupOp);
7127 }
Rex Xu51596642016-09-21 18:56:12 +08007128 }
7129
John Kessenich149afc32018-08-14 13:31:43 -06007130 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
7131 spv::IdImmediate op = { true, *opIt };
7132 spvGroupOperands.push_back(op);
7133 }
John Kessenich91cef522016-05-05 16:45:40 -06007134
7135 switch (op) {
7136 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007137 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08007138 break;
John Kessenich91cef522016-05-05 16:45:40 -06007139 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007140 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08007141 break;
John Kessenich91cef522016-05-05 16:45:40 -06007142 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007143 opCode = spv::OpSubgroupAllEqualKHR;
7144 break;
Rex Xu51596642016-09-21 18:56:12 +08007145 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08007146 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08007147 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007148 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007149 break;
7150 case glslang::EOpReadFirstInvocation:
7151 opCode = spv::OpSubgroupFirstInvocationKHR;
7152 break;
7153 case glslang::EOpBallot:
7154 {
7155 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
7156 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
7157 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
7158 //
7159 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
7160 //
7161 spv::Id uintType = builder.makeUintType(32);
7162 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
7163 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
7164
7165 std::vector<spv::Id> components;
7166 components.push_back(builder.createCompositeExtract(result, uintType, 0));
7167 components.push_back(builder.createCompositeExtract(result, uintType, 1));
7168
7169 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
7170 return builder.createUnaryOp(spv::OpBitcast, typeId,
7171 builder.createCompositeConstruct(uvec2Type, components));
7172 }
7173
Rex Xu9d93a232016-05-05 12:30:44 +08007174 case glslang::EOpMinInvocations:
7175 case glslang::EOpMaxInvocations:
7176 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08007177 case glslang::EOpMinInvocationsInclusiveScan:
7178 case glslang::EOpMaxInvocationsInclusiveScan:
7179 case glslang::EOpAddInvocationsInclusiveScan:
7180 case glslang::EOpMinInvocationsExclusiveScan:
7181 case glslang::EOpMaxInvocationsExclusiveScan:
7182 case glslang::EOpAddInvocationsExclusiveScan:
7183 if (op == glslang::EOpMinInvocations ||
7184 op == glslang::EOpMinInvocationsInclusiveScan ||
7185 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007186 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007187 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007188 else {
7189 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007190 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007191 else
Rex Xu51596642016-09-21 18:56:12 +08007192 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007193 }
Rex Xu430ef402016-10-14 17:22:23 +08007194 } else if (op == glslang::EOpMaxInvocations ||
7195 op == glslang::EOpMaxInvocationsInclusiveScan ||
7196 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007197 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007198 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007199 else {
7200 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007201 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007202 else
Rex Xu51596642016-09-21 18:56:12 +08007203 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007204 }
7205 } else {
7206 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007207 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007208 else
Rex Xu51596642016-09-21 18:56:12 +08007209 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007210 }
7211
Rex Xu2bbbe062016-08-23 15:41:05 +08007212 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007213 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007214
7215 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007216 case glslang::EOpMinInvocationsNonUniform:
7217 case glslang::EOpMaxInvocationsNonUniform:
7218 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007219 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7220 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7221 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7222 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7223 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7224 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7225 if (op == glslang::EOpMinInvocationsNonUniform ||
7226 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7227 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007228 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007229 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007230 else {
7231 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007232 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007233 else
Rex Xu51596642016-09-21 18:56:12 +08007234 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007235 }
7236 }
Rex Xu430ef402016-10-14 17:22:23 +08007237 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7238 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7239 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007240 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007241 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007242 else {
7243 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007244 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007245 else
Rex Xu51596642016-09-21 18:56:12 +08007246 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007247 }
7248 }
7249 else {
7250 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007251 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007252 else
Rex Xu51596642016-09-21 18:56:12 +08007253 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007254 }
7255
Rex Xu2bbbe062016-08-23 15:41:05 +08007256 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007257 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007258
7259 break;
John Kessenich91cef522016-05-05 16:45:40 -06007260 default:
7261 logger->missingFunctionality("invocation operation");
7262 return spv::NoResult;
7263 }
Rex Xu51596642016-09-21 18:56:12 +08007264
7265 assert(opCode != spv::OpNop);
7266 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007267}
7268
Rex Xu2bbbe062016-08-23 15:41:05 +08007269// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007270spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7271 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007272{
7273 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7274 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007275 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007276 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007277 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7278 op == spv::OpGroupSMinNonUniformAMD ||
7279 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7280 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007281 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7282
7283 // Handle group invocation operations scalar by scalar.
7284 // The result type is the same type as the original type.
7285 // The algorithm is to:
7286 // - break the vector into scalars
7287 // - apply the operation to each scalar
7288 // - make a vector out the scalar results
7289
7290 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007291 int numComponents = builder.getNumComponents(operands[0]);
7292 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007293 std::vector<spv::Id> results;
7294
7295 // do each scalar op
7296 for (int comp = 0; comp < numComponents; ++comp) {
7297 std::vector<unsigned int> indexes;
7298 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007299 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7300 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007301 if (op == spv::OpSubgroupReadInvocationKHR) {
7302 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007303 spv::IdImmediate operand = { true, operands[1] };
7304 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007305 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007306 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7307 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007308 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007309 spv::IdImmediate operand = { true, operands[1] };
7310 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007311 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007312 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7313 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007314 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007315 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007316 spvGroupOperands.push_back(scalar);
7317 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007318
Rex Xub7072052016-09-26 15:53:40 +08007319 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007320 }
7321
7322 // put the pieces together
7323 return builder.createCompositeConstruct(typeId, results);
7324}
Rex Xu2bbbe062016-08-23 15:41:05 +08007325
John Kessenich66011cb2018-03-06 16:12:04 -07007326// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007327spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7328 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007329{
7330 // Add the required capabilities.
7331 switch (op) {
7332 case glslang::EOpSubgroupElect:
7333 builder.addCapability(spv::CapabilityGroupNonUniform);
7334 break;
7335 case glslang::EOpSubgroupAll:
7336 case glslang::EOpSubgroupAny:
7337 case glslang::EOpSubgroupAllEqual:
7338 builder.addCapability(spv::CapabilityGroupNonUniform);
7339 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7340 break;
7341 case glslang::EOpSubgroupBroadcast:
7342 case glslang::EOpSubgroupBroadcastFirst:
7343 case glslang::EOpSubgroupBallot:
7344 case glslang::EOpSubgroupInverseBallot:
7345 case glslang::EOpSubgroupBallotBitExtract:
7346 case glslang::EOpSubgroupBallotBitCount:
7347 case glslang::EOpSubgroupBallotInclusiveBitCount:
7348 case glslang::EOpSubgroupBallotExclusiveBitCount:
7349 case glslang::EOpSubgroupBallotFindLSB:
7350 case glslang::EOpSubgroupBallotFindMSB:
7351 builder.addCapability(spv::CapabilityGroupNonUniform);
7352 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7353 break;
7354 case glslang::EOpSubgroupShuffle:
7355 case glslang::EOpSubgroupShuffleXor:
7356 builder.addCapability(spv::CapabilityGroupNonUniform);
7357 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7358 break;
7359 case glslang::EOpSubgroupShuffleUp:
7360 case glslang::EOpSubgroupShuffleDown:
7361 builder.addCapability(spv::CapabilityGroupNonUniform);
7362 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7363 break;
7364 case glslang::EOpSubgroupAdd:
7365 case glslang::EOpSubgroupMul:
7366 case glslang::EOpSubgroupMin:
7367 case glslang::EOpSubgroupMax:
7368 case glslang::EOpSubgroupAnd:
7369 case glslang::EOpSubgroupOr:
7370 case glslang::EOpSubgroupXor:
7371 case glslang::EOpSubgroupInclusiveAdd:
7372 case glslang::EOpSubgroupInclusiveMul:
7373 case glslang::EOpSubgroupInclusiveMin:
7374 case glslang::EOpSubgroupInclusiveMax:
7375 case glslang::EOpSubgroupInclusiveAnd:
7376 case glslang::EOpSubgroupInclusiveOr:
7377 case glslang::EOpSubgroupInclusiveXor:
7378 case glslang::EOpSubgroupExclusiveAdd:
7379 case glslang::EOpSubgroupExclusiveMul:
7380 case glslang::EOpSubgroupExclusiveMin:
7381 case glslang::EOpSubgroupExclusiveMax:
7382 case glslang::EOpSubgroupExclusiveAnd:
7383 case glslang::EOpSubgroupExclusiveOr:
7384 case glslang::EOpSubgroupExclusiveXor:
7385 builder.addCapability(spv::CapabilityGroupNonUniform);
7386 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7387 break;
7388 case glslang::EOpSubgroupClusteredAdd:
7389 case glslang::EOpSubgroupClusteredMul:
7390 case glslang::EOpSubgroupClusteredMin:
7391 case glslang::EOpSubgroupClusteredMax:
7392 case glslang::EOpSubgroupClusteredAnd:
7393 case glslang::EOpSubgroupClusteredOr:
7394 case glslang::EOpSubgroupClusteredXor:
7395 builder.addCapability(spv::CapabilityGroupNonUniform);
7396 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7397 break;
7398 case glslang::EOpSubgroupQuadBroadcast:
7399 case glslang::EOpSubgroupQuadSwapHorizontal:
7400 case glslang::EOpSubgroupQuadSwapVertical:
7401 case glslang::EOpSubgroupQuadSwapDiagonal:
7402 builder.addCapability(spv::CapabilityGroupNonUniform);
7403 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7404 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007405 case glslang::EOpSubgroupPartitionedAdd:
7406 case glslang::EOpSubgroupPartitionedMul:
7407 case glslang::EOpSubgroupPartitionedMin:
7408 case glslang::EOpSubgroupPartitionedMax:
7409 case glslang::EOpSubgroupPartitionedAnd:
7410 case glslang::EOpSubgroupPartitionedOr:
7411 case glslang::EOpSubgroupPartitionedXor:
7412 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7413 case glslang::EOpSubgroupPartitionedInclusiveMul:
7414 case glslang::EOpSubgroupPartitionedInclusiveMin:
7415 case glslang::EOpSubgroupPartitionedInclusiveMax:
7416 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7417 case glslang::EOpSubgroupPartitionedInclusiveOr:
7418 case glslang::EOpSubgroupPartitionedInclusiveXor:
7419 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7420 case glslang::EOpSubgroupPartitionedExclusiveMul:
7421 case glslang::EOpSubgroupPartitionedExclusiveMin:
7422 case glslang::EOpSubgroupPartitionedExclusiveMax:
7423 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7424 case glslang::EOpSubgroupPartitionedExclusiveOr:
7425 case glslang::EOpSubgroupPartitionedExclusiveXor:
7426 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7427 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7428 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007429 default: assert(0 && "Unhandled subgroup operation!");
7430 }
7431
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007432
7433 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7434 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007435 const bool isBool = typeProxy == glslang::EbtBool;
7436
7437 spv::Op opCode = spv::OpNop;
7438
7439 // Figure out which opcode to use.
7440 switch (op) {
7441 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7442 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7443 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7444 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7445 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7446 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7447 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7448 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7449 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7450 case glslang::EOpSubgroupBallotBitCount:
7451 case glslang::EOpSubgroupBallotInclusiveBitCount:
7452 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7453 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7454 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7455 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7456 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7457 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7458 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7459 case glslang::EOpSubgroupAdd:
7460 case glslang::EOpSubgroupInclusiveAdd:
7461 case glslang::EOpSubgroupExclusiveAdd:
7462 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007463 case glslang::EOpSubgroupPartitionedAdd:
7464 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7465 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007466 if (isFloat) {
7467 opCode = spv::OpGroupNonUniformFAdd;
7468 } else {
7469 opCode = spv::OpGroupNonUniformIAdd;
7470 }
7471 break;
7472 case glslang::EOpSubgroupMul:
7473 case glslang::EOpSubgroupInclusiveMul:
7474 case glslang::EOpSubgroupExclusiveMul:
7475 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007476 case glslang::EOpSubgroupPartitionedMul:
7477 case glslang::EOpSubgroupPartitionedInclusiveMul:
7478 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007479 if (isFloat) {
7480 opCode = spv::OpGroupNonUniformFMul;
7481 } else {
7482 opCode = spv::OpGroupNonUniformIMul;
7483 }
7484 break;
7485 case glslang::EOpSubgroupMin:
7486 case glslang::EOpSubgroupInclusiveMin:
7487 case glslang::EOpSubgroupExclusiveMin:
7488 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007489 case glslang::EOpSubgroupPartitionedMin:
7490 case glslang::EOpSubgroupPartitionedInclusiveMin:
7491 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007492 if (isFloat) {
7493 opCode = spv::OpGroupNonUniformFMin;
7494 } else if (isUnsigned) {
7495 opCode = spv::OpGroupNonUniformUMin;
7496 } else {
7497 opCode = spv::OpGroupNonUniformSMin;
7498 }
7499 break;
7500 case glslang::EOpSubgroupMax:
7501 case glslang::EOpSubgroupInclusiveMax:
7502 case glslang::EOpSubgroupExclusiveMax:
7503 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007504 case glslang::EOpSubgroupPartitionedMax:
7505 case glslang::EOpSubgroupPartitionedInclusiveMax:
7506 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007507 if (isFloat) {
7508 opCode = spv::OpGroupNonUniformFMax;
7509 } else if (isUnsigned) {
7510 opCode = spv::OpGroupNonUniformUMax;
7511 } else {
7512 opCode = spv::OpGroupNonUniformSMax;
7513 }
7514 break;
7515 case glslang::EOpSubgroupAnd:
7516 case glslang::EOpSubgroupInclusiveAnd:
7517 case glslang::EOpSubgroupExclusiveAnd:
7518 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007519 case glslang::EOpSubgroupPartitionedAnd:
7520 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7521 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007522 if (isBool) {
7523 opCode = spv::OpGroupNonUniformLogicalAnd;
7524 } else {
7525 opCode = spv::OpGroupNonUniformBitwiseAnd;
7526 }
7527 break;
7528 case glslang::EOpSubgroupOr:
7529 case glslang::EOpSubgroupInclusiveOr:
7530 case glslang::EOpSubgroupExclusiveOr:
7531 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007532 case glslang::EOpSubgroupPartitionedOr:
7533 case glslang::EOpSubgroupPartitionedInclusiveOr:
7534 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007535 if (isBool) {
7536 opCode = spv::OpGroupNonUniformLogicalOr;
7537 } else {
7538 opCode = spv::OpGroupNonUniformBitwiseOr;
7539 }
7540 break;
7541 case glslang::EOpSubgroupXor:
7542 case glslang::EOpSubgroupInclusiveXor:
7543 case glslang::EOpSubgroupExclusiveXor:
7544 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007545 case glslang::EOpSubgroupPartitionedXor:
7546 case glslang::EOpSubgroupPartitionedInclusiveXor:
7547 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007548 if (isBool) {
7549 opCode = spv::OpGroupNonUniformLogicalXor;
7550 } else {
7551 opCode = spv::OpGroupNonUniformBitwiseXor;
7552 }
7553 break;
7554 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7555 case glslang::EOpSubgroupQuadSwapHorizontal:
7556 case glslang::EOpSubgroupQuadSwapVertical:
7557 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7558 default: assert(0 && "Unhandled subgroup operation!");
7559 }
7560
John Kessenich149afc32018-08-14 13:31:43 -06007561 // get the right Group Operation
7562 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007563 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007564 default:
7565 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007566 case glslang::EOpSubgroupBallotBitCount:
7567 case glslang::EOpSubgroupAdd:
7568 case glslang::EOpSubgroupMul:
7569 case glslang::EOpSubgroupMin:
7570 case glslang::EOpSubgroupMax:
7571 case glslang::EOpSubgroupAnd:
7572 case glslang::EOpSubgroupOr:
7573 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007574 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007575 break;
7576 case glslang::EOpSubgroupBallotInclusiveBitCount:
7577 case glslang::EOpSubgroupInclusiveAdd:
7578 case glslang::EOpSubgroupInclusiveMul:
7579 case glslang::EOpSubgroupInclusiveMin:
7580 case glslang::EOpSubgroupInclusiveMax:
7581 case glslang::EOpSubgroupInclusiveAnd:
7582 case glslang::EOpSubgroupInclusiveOr:
7583 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007584 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007585 break;
7586 case glslang::EOpSubgroupBallotExclusiveBitCount:
7587 case glslang::EOpSubgroupExclusiveAdd:
7588 case glslang::EOpSubgroupExclusiveMul:
7589 case glslang::EOpSubgroupExclusiveMin:
7590 case glslang::EOpSubgroupExclusiveMax:
7591 case glslang::EOpSubgroupExclusiveAnd:
7592 case glslang::EOpSubgroupExclusiveOr:
7593 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007594 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007595 break;
7596 case glslang::EOpSubgroupClusteredAdd:
7597 case glslang::EOpSubgroupClusteredMul:
7598 case glslang::EOpSubgroupClusteredMin:
7599 case glslang::EOpSubgroupClusteredMax:
7600 case glslang::EOpSubgroupClusteredAnd:
7601 case glslang::EOpSubgroupClusteredOr:
7602 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007603 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007604 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007605 case glslang::EOpSubgroupPartitionedAdd:
7606 case glslang::EOpSubgroupPartitionedMul:
7607 case glslang::EOpSubgroupPartitionedMin:
7608 case glslang::EOpSubgroupPartitionedMax:
7609 case glslang::EOpSubgroupPartitionedAnd:
7610 case glslang::EOpSubgroupPartitionedOr:
7611 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007612 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007613 break;
7614 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7615 case glslang::EOpSubgroupPartitionedInclusiveMul:
7616 case glslang::EOpSubgroupPartitionedInclusiveMin:
7617 case glslang::EOpSubgroupPartitionedInclusiveMax:
7618 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7619 case glslang::EOpSubgroupPartitionedInclusiveOr:
7620 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007621 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007622 break;
7623 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7624 case glslang::EOpSubgroupPartitionedExclusiveMul:
7625 case glslang::EOpSubgroupPartitionedExclusiveMin:
7626 case glslang::EOpSubgroupPartitionedExclusiveMax:
7627 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7628 case glslang::EOpSubgroupPartitionedExclusiveOr:
7629 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007630 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007631 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007632 }
7633
John Kessenich149afc32018-08-14 13:31:43 -06007634 // build the instruction
7635 std::vector<spv::IdImmediate> spvGroupOperands;
7636
7637 // Every operation begins with the Execution Scope operand.
7638 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7639 spvGroupOperands.push_back(executionScope);
7640
7641 // Next, for all operations that use a Group Operation, push that as an operand.
7642 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007643 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007644 spvGroupOperands.push_back(groupOperand);
7645 }
7646
John Kessenich66011cb2018-03-06 16:12:04 -07007647 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007648 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7649 spv::IdImmediate operand = { true, *opIt };
7650 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007651 }
7652
7653 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007654 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007655 switch (op) {
7656 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007657 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7658 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7659 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7660 }
7661 if (directionId != spv::NoResult) {
7662 spv::IdImmediate direction = { true, directionId };
7663 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007664 }
7665
7666 return builder.createOp(opCode, typeId, spvGroupOperands);
7667}
7668
John Kessenich8985fc92020-03-03 10:25:07 -07007669spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7670 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007671{
John Kessenich66011cb2018-03-06 16:12:04 -07007672 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7673 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007674
John Kessenich140f3df2015-06-26 16:58:36 -06007675 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007676 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007677 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007678 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007679 spv::Id typeId0 = 0;
7680 if (consumedOperands > 0)
7681 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007682 spv::Id typeId1 = 0;
7683 if (consumedOperands > 1)
7684 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007685 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007686
7687 switch (op) {
7688 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007689 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007690 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007691 else if (isUnsigned)
7692 libCall = spv::GLSLstd450UMin;
7693 else
7694 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007695 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007696 break;
7697 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007698 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007699 break;
7700 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007701 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007702 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007703 else if (isUnsigned)
7704 libCall = spv::GLSLstd450UMax;
7705 else
7706 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007707 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007708 break;
7709 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007710 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007711 break;
7712 case glslang::EOpDot:
7713 opCode = spv::OpDot;
7714 break;
7715 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007716 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007717 break;
7718
7719 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007720 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007721 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007722 else if (isUnsigned)
7723 libCall = spv::GLSLstd450UClamp;
7724 else
7725 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007726 builder.promoteScalar(precision, operands.front(), operands[1]);
7727 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007728 break;
7729 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007730 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7731 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007732 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007733 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007734 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007735 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007736 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007737 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007738 break;
7739 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007740 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007741 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007742 break;
7743 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007744 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007745 builder.promoteScalar(precision, operands[0], operands[2]);
7746 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007747 break;
7748
7749 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007750 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007751 break;
7752 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007753 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007754 break;
7755 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007756 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007757 break;
7758 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007759 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007760 break;
7761 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007762 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007763 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007764 case glslang::EOpBarrier:
7765 {
7766 // This is for the extended controlBarrier function, with four operands.
7767 // The unextended barrier() goes through createNoArgOperation.
7768 assert(operands.size() == 4);
7769 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7770 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7771 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007772 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7773 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007774 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7775 spv::MemorySemanticsMakeVisibleKHRMask |
7776 spv::MemorySemanticsOutputMemoryKHRMask |
7777 spv::MemorySemanticsVolatileMask)) {
7778 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7779 }
John Kessenich8985fc92020-03-03 10:25:07 -07007780 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7781 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007782 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7783 }
7784 return 0;
7785 }
7786 break;
7787 case glslang::EOpMemoryBarrier:
7788 {
7789 // This is for the extended memoryBarrier function, with three operands.
7790 // The unextended memoryBarrier() goes through createNoArgOperation.
7791 assert(operands.size() == 3);
7792 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7793 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7794 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7795 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7796 spv::MemorySemanticsMakeVisibleKHRMask |
7797 spv::MemorySemanticsOutputMemoryKHRMask |
7798 spv::MemorySemanticsVolatileMask)) {
7799 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7800 }
7801 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7802 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7803 }
7804 return 0;
7805 }
7806 break;
7807
John Kessenicha28f7a72019-08-06 07:00:58 -06007808#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007809 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007810 if (typeProxy == glslang::EbtFloat16)
7811 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007812 libCall = spv::GLSLstd450InterpolateAtSample;
7813 break;
7814 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007815 if (typeProxy == glslang::EbtFloat16)
7816 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007817 libCall = spv::GLSLstd450InterpolateAtOffset;
7818 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007819 case glslang::EOpAddCarry:
7820 opCode = spv::OpIAddCarry;
7821 typeId = builder.makeStructResultType(typeId0, typeId0);
7822 consumedOperands = 2;
7823 break;
7824 case glslang::EOpSubBorrow:
7825 opCode = spv::OpISubBorrow;
7826 typeId = builder.makeStructResultType(typeId0, typeId0);
7827 consumedOperands = 2;
7828 break;
7829 case glslang::EOpUMulExtended:
7830 opCode = spv::OpUMulExtended;
7831 typeId = builder.makeStructResultType(typeId0, typeId0);
7832 consumedOperands = 2;
7833 break;
7834 case glslang::EOpIMulExtended:
7835 opCode = spv::OpSMulExtended;
7836 typeId = builder.makeStructResultType(typeId0, typeId0);
7837 consumedOperands = 2;
7838 break;
7839 case glslang::EOpBitfieldExtract:
7840 if (isUnsigned)
7841 opCode = spv::OpBitFieldUExtract;
7842 else
7843 opCode = spv::OpBitFieldSExtract;
7844 break;
7845 case glslang::EOpBitfieldInsert:
7846 opCode = spv::OpBitFieldInsert;
7847 break;
7848
7849 case glslang::EOpFma:
7850 libCall = spv::GLSLstd450Fma;
7851 break;
7852 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007853 {
7854 libCall = spv::GLSLstd450FrexpStruct;
7855 assert(builder.isPointerType(typeId1));
7856 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007857 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007858 if (width == 16)
7859 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7860 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007861 if (builder.getNumComponents(operands[0]) == 1)
7862 frexpIntType = builder.makeIntegerType(width, true);
7863 else
John Kessenich8985fc92020-03-03 10:25:07 -07007864 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7865 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007866 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7867 consumedOperands = 1;
7868 }
John Kessenich55e7d112015-11-15 21:33:39 -07007869 break;
7870 case glslang::EOpLdexp:
7871 libCall = spv::GLSLstd450Ldexp;
7872 break;
7873
Rex Xu574ab042016-04-14 16:53:07 +08007874 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007875 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007876
John Kessenich66011cb2018-03-06 16:12:04 -07007877 case glslang::EOpSubgroupBroadcast:
7878 case glslang::EOpSubgroupBallotBitExtract:
7879 case glslang::EOpSubgroupShuffle:
7880 case glslang::EOpSubgroupShuffleXor:
7881 case glslang::EOpSubgroupShuffleUp:
7882 case glslang::EOpSubgroupShuffleDown:
7883 case glslang::EOpSubgroupClusteredAdd:
7884 case glslang::EOpSubgroupClusteredMul:
7885 case glslang::EOpSubgroupClusteredMin:
7886 case glslang::EOpSubgroupClusteredMax:
7887 case glslang::EOpSubgroupClusteredAnd:
7888 case glslang::EOpSubgroupClusteredOr:
7889 case glslang::EOpSubgroupClusteredXor:
7890 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007891 case glslang::EOpSubgroupPartitionedAdd:
7892 case glslang::EOpSubgroupPartitionedMul:
7893 case glslang::EOpSubgroupPartitionedMin:
7894 case glslang::EOpSubgroupPartitionedMax:
7895 case glslang::EOpSubgroupPartitionedAnd:
7896 case glslang::EOpSubgroupPartitionedOr:
7897 case glslang::EOpSubgroupPartitionedXor:
7898 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7899 case glslang::EOpSubgroupPartitionedInclusiveMul:
7900 case glslang::EOpSubgroupPartitionedInclusiveMin:
7901 case glslang::EOpSubgroupPartitionedInclusiveMax:
7902 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7903 case glslang::EOpSubgroupPartitionedInclusiveOr:
7904 case glslang::EOpSubgroupPartitionedInclusiveXor:
7905 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7906 case glslang::EOpSubgroupPartitionedExclusiveMul:
7907 case glslang::EOpSubgroupPartitionedExclusiveMin:
7908 case glslang::EOpSubgroupPartitionedExclusiveMax:
7909 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7910 case glslang::EOpSubgroupPartitionedExclusiveOr:
7911 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007912 return createSubgroupOperation(op, typeId, operands, typeProxy);
7913
Rex Xu9d93a232016-05-05 12:30:44 +08007914 case glslang::EOpSwizzleInvocations:
7915 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7916 libCall = spv::SwizzleInvocationsAMD;
7917 break;
7918 case glslang::EOpSwizzleInvocationsMasked:
7919 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7920 libCall = spv::SwizzleInvocationsMaskedAMD;
7921 break;
7922 case glslang::EOpWriteInvocation:
7923 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7924 libCall = spv::WriteInvocationAMD;
7925 break;
7926
7927 case glslang::EOpMin3:
7928 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7929 if (isFloat)
7930 libCall = spv::FMin3AMD;
7931 else {
7932 if (isUnsigned)
7933 libCall = spv::UMin3AMD;
7934 else
7935 libCall = spv::SMin3AMD;
7936 }
7937 break;
7938 case glslang::EOpMax3:
7939 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7940 if (isFloat)
7941 libCall = spv::FMax3AMD;
7942 else {
7943 if (isUnsigned)
7944 libCall = spv::UMax3AMD;
7945 else
7946 libCall = spv::SMax3AMD;
7947 }
7948 break;
7949 case glslang::EOpMid3:
7950 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7951 if (isFloat)
7952 libCall = spv::FMid3AMD;
7953 else {
7954 if (isUnsigned)
7955 libCall = spv::UMid3AMD;
7956 else
7957 libCall = spv::SMid3AMD;
7958 }
7959 break;
7960
7961 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007962 if (typeProxy == glslang::EbtFloat16)
7963 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007964 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7965 libCall = spv::InterpolateAtVertexAMD;
7966 break;
Chao Chen3c366992018-09-19 11:41:59 -07007967
Daniel Kochdb32b242020-03-17 20:42:47 -04007968 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007969 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007970 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007971 break;
Daniel Kochffccefd2020-11-23 15:41:27 -05007972 case glslang::EOpTraceNV:
7973 builder.createNoResultOp(spv::OpTraceNV, operands);
7974 return 0;
7975 case glslang::EOpTraceKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007976 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007977 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05007978 case glslang::EOpExecuteCallableNV:
7979 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
7980 return 0;
7981 case glslang::EOpExecuteCallableKHR:
Daniel Kochdb32b242020-03-17 20:42:47 -04007982 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007983 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007984
7985 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007986 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7987 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007988 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007989 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7990 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007991 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007992 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7993 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007994 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007995 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7996 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007997 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007998 typeId = builder.makeBoolType();
7999 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008000 break;
8001 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04008002 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04008003 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008004 break;
8005 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04008006 typeId = builder.makeFloatType(32);
8007 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008008 break;
8009 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04008010 typeId = builder.makeIntType(32);
8011 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008012 break;
8013 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04008014 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04008015 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008016 break;
8017 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04008018 typeId = builder.makeIntType(32);
8019 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008020 break;
8021 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04008022 typeId = builder.makeIntType(32);
8023 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008024 break;
8025 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Daniel Kochc0bcfaf2020-12-12 12:34:24 -05008026 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04008027 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008028 break;
8029 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04008030 typeId = builder.makeIntType(32);
8031 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008032 break;
8033 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04008034 typeId = builder.makeIntType(32);
8035 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008036 break;
8037 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04008038 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
8039 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008040 break;
8041 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04008042 typeId = builder.makeBoolType();
8043 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008044 break;
8045 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04008046 typeId = builder.makeBoolType();
8047 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008048 break;
8049 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04008050 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8051 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008052 break;
8053 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04008054 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8055 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008056 break;
8057 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04008058 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8059 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008060 break;
8061 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04008062 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
8063 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008064 break;
8065 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04008066 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04008067 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008068 break;
8069 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04008070 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04008071 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04008072 break;
Chao Chen3c366992018-09-19 11:41:59 -07008073 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
8074 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
8075 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008076 case glslang::EOpCooperativeMatrixMulAdd:
8077 opCode = spv::OpCooperativeMatrixMulAddNV;
8078 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06008079#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06008080 default:
8081 return 0;
8082 }
8083
8084 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07008085 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05008086 // Use an extended instruction from the standard library.
8087 // Construct the call arguments, without modifying the original operands vector.
8088 // We might need the remaining arguments, e.g. in the EOpFrexp case.
8089 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08008090 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01008091 } else if (opCode == spv::OpDot && !isFloat) {
8092 // int dot(int, int)
8093 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
8094 const int componentCount = builder.getNumComponents(operands[0]);
8095 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
8096 builder.setPrecision(mulOp, precision);
8097 id = builder.createCompositeExtract(mulOp, typeId, 0);
8098 for (int i = 1; i < componentCount; ++i) {
8099 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07008100 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01008101 }
John Kessenich2359bd02015-12-06 19:29:11 -07008102 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07008103 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06008104 case 0:
8105 // should all be handled by visitAggregate and createNoArgOperation
8106 assert(0);
8107 return 0;
8108 case 1:
8109 // should all be handled by createUnaryOperation
8110 assert(0);
8111 return 0;
8112 case 2:
8113 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
8114 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008115 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008116 // anything 3 or over doesn't have l-value operands, so all should be consumed
8117 assert(consumedOperands == operands.size());
8118 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06008119 break;
8120 }
8121 }
8122
John Kessenichb9197c82019-08-11 07:41:45 -06008123#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07008124 // Decode the return types that were structures
8125 switch (op) {
8126 case glslang::EOpAddCarry:
8127 case glslang::EOpSubBorrow:
8128 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8129 id = builder.createCompositeExtract(id, typeId0, 0);
8130 break;
8131 case glslang::EOpUMulExtended:
8132 case glslang::EOpIMulExtended:
8133 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
8134 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8135 break;
8136 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08008137 {
8138 assert(operands.size() == 2);
8139 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
8140 // "exp" is floating-point type (from HLSL intrinsic)
8141 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
8142 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
8143 builder.createStore(member1, operands[1]);
8144 } else
8145 // "exp" is integer type (from GLSL built-in function)
8146 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
8147 id = builder.createCompositeExtract(id, typeId0, 0);
8148 }
John Kessenich55e7d112015-11-15 21:33:39 -07008149 break;
8150 default:
8151 break;
8152 }
John Kessenichb9197c82019-08-11 07:41:45 -06008153#endif
John Kessenich55e7d112015-11-15 21:33:39 -07008154
John Kessenich32cfd492016-02-02 12:37:46 -07008155 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06008156}
8157
Rex Xu9d93a232016-05-05 12:30:44 +08008158// Intrinsics with no arguments (or no return value, and no precision).
8159spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06008160{
Jeff Bolz36831c92018-09-05 10:11:41 -05008161 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07008162 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
8163 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06008164
8165 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06008166 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008167 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05008168 if (glslangIntermediate->usingVulkanMemoryModel()) {
8169 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8170 spv::MemorySemanticsOutputMemoryKHRMask |
8171 spv::MemorySemanticsAcquireReleaseMask);
8172 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
8173 } else {
8174 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
8175 }
John Kessenich82979362017-12-11 04:02:24 -07008176 } else {
8177 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8178 spv::MemorySemanticsWorkgroupMemoryMask |
8179 spv::MemorySemanticsAcquireReleaseMask);
8180 }
John Kessenich140f3df2015-06-26 16:58:36 -06008181 return 0;
8182 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05008183 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
8184 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008185 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008186 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05008187 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
8188 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008189 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008190 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05008191 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
8192 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008193 return 0;
8194 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008195 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
8196 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008197 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06008198#ifndef GLSLANG_WEB
8199 case glslang::EOpMemoryBarrierAtomicCounter:
8200 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
8201 spv::MemorySemanticsAcquireReleaseMask);
8202 return 0;
8203 case glslang::EOpMemoryBarrierImage:
8204 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8205 spv::MemorySemanticsAcquireReleaseMask);
8206 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008207 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008208 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008209 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008210 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008211 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008212 case glslang::EOpDeviceMemoryBarrier:
8213 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8214 spv::MemorySemanticsImageMemoryMask |
8215 spv::MemorySemanticsAcquireReleaseMask);
8216 return 0;
8217 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8218 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8219 spv::MemorySemanticsImageMemoryMask |
8220 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008221 return 0;
8222 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008223 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8224 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008225 return 0;
8226 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008227 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8228 spv::MemorySemanticsWorkgroupMemoryMask |
8229 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008230 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008231 case glslang::EOpSubgroupBarrier:
8232 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8233 spv::MemorySemanticsAcquireReleaseMask);
8234 return spv::NoResult;
8235 case glslang::EOpSubgroupMemoryBarrier:
8236 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8237 spv::MemorySemanticsAcquireReleaseMask);
8238 return spv::NoResult;
8239 case glslang::EOpSubgroupMemoryBarrierBuffer:
8240 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8241 spv::MemorySemanticsAcquireReleaseMask);
8242 return spv::NoResult;
8243 case glslang::EOpSubgroupMemoryBarrierImage:
8244 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8245 spv::MemorySemanticsAcquireReleaseMask);
8246 return spv::NoResult;
8247 case glslang::EOpSubgroupMemoryBarrierShared:
8248 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8249 spv::MemorySemanticsAcquireReleaseMask);
8250 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008251
8252 case glslang::EOpEmitVertex:
8253 builder.createNoResultOp(spv::OpEmitVertex);
8254 return 0;
8255 case glslang::EOpEndPrimitive:
8256 builder.createNoResultOp(spv::OpEndPrimitive);
8257 return 0;
8258
John Kessenich66011cb2018-03-06 16:12:04 -07008259 case glslang::EOpSubgroupElect: {
8260 std::vector<spv::Id> operands;
8261 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8262 }
Rex Xu9d93a232016-05-05 12:30:44 +08008263 case glslang::EOpTime:
8264 {
8265 std::vector<spv::Id> args; // Dummy arguments
8266 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8267 return builder.setPrecision(id, precision);
8268 }
Daniel Kochffccefd2020-11-23 15:41:27 -05008269 case glslang::EOpIgnoreIntersectionNV:
8270 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008271 return 0;
Daniel Kochffccefd2020-11-23 15:41:27 -05008272 case glslang::EOpTerminateRayNV:
8273 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07008274 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008275 case glslang::EOpRayQueryInitialize:
8276 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8277 return 0;
8278 case glslang::EOpRayQueryTerminate:
8279 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8280 return 0;
8281 case glslang::EOpRayQueryGenerateIntersection:
8282 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8283 return 0;
8284 case glslang::EOpRayQueryConfirmIntersection:
8285 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8286 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008287 case glslang::EOpBeginInvocationInterlock:
8288 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8289 return 0;
8290 case glslang::EOpEndInvocationInterlock:
8291 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8292 return 0;
8293
Jeff Bolzba6170b2019-07-01 09:23:23 -05008294 case glslang::EOpIsHelperInvocation:
8295 {
8296 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008297 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8298 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8299 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008300 }
8301
amhagan91fb0092019-07-10 21:14:38 -04008302 case glslang::EOpReadClockSubgroupKHR: {
8303 std::vector<spv::Id> args;
8304 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8305 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8306 builder.addCapability(spv::CapabilityShaderClockKHR);
8307 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8308 }
8309
8310 case glslang::EOpReadClockDeviceKHR: {
8311 std::vector<spv::Id> args;
8312 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8313 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8314 builder.addCapability(spv::CapabilityShaderClockKHR);
8315 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8316 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008317#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008318 default:
John Kessenich155d3512019-08-08 23:29:20 -06008319 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008320 }
John Kessenich155d3512019-08-08 23:29:20 -06008321
8322 logger->missingFunctionality("unknown operation with no arguments");
8323
8324 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008325}
8326
8327spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8328{
John Kessenich2f273362015-07-18 22:34:27 -06008329 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008330 spv::Id id;
8331 if (symbolValues.end() != iter) {
8332 id = iter->second;
8333 return id;
8334 }
8335
8336 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008337 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008338 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008339 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008340 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008341 if (forcedType.second != spv::NoType)
8342 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008343
Rex Xuc884b4a2016-06-29 15:03:44 +08008344 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008345 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8346 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8347 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008348#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008349 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008350 if (symbol->getQualifier().hasComponent())
8351 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8352 if (symbol->getQualifier().hasIndex())
8353 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008354#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008355 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008356 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008357 // atomic counters use this:
8358 if (symbol->getQualifier().hasOffset())
8359 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008360 }
8361
scygan2c864272016-05-18 18:09:17 +02008362 if (symbol->getQualifier().hasLocation())
8363 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008364 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008365 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008366 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008367 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008368 }
John Kessenich140f3df2015-06-26 16:58:36 -06008369 if (symbol->getQualifier().hasSet())
8370 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008371 else if (IsDescriptorResource(symbol->getType())) {
8372 // default to 0
8373 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8374 }
John Kessenich140f3df2015-06-26 16:58:36 -06008375 if (symbol->getQualifier().hasBinding())
8376 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008377 else if (IsDescriptorResource(symbol->getType())) {
8378 // default to 0
8379 builder.addDecoration(id, spv::DecorationBinding, 0);
8380 }
John Kessenich6c292d32016-02-15 20:58:50 -07008381 if (symbol->getQualifier().hasAttachment())
8382 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008383 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008384 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008385 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008386 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008387 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8388 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8389 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8390 }
8391 if (symbol->getQualifier().hasXfbOffset())
8392 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008393 }
8394
John Kessenichb9197c82019-08-11 07:41:45 -06008395 // add built-in variable decoration
8396 if (builtIn != spv::BuiltInMax) {
8397 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8398 }
8399
8400#ifndef GLSLANG_WEB
Daniel Kochffccefd2020-11-23 15:41:27 -05008401 // Subgroup builtins which have input storage class are volatile for ray tracing stages.
8402 if (symbol->getType().isImage() || symbol->getQualifier().isPipeInput()) {
Rex Xu1da878f2016-02-21 20:59:01 +08008403 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008404 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8405 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008406 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008407 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008408 }
8409
chaoc0ad6a4e2016-12-19 16:29:34 -08008410 if (builtIn == spv::BuiltInSampleMask) {
8411 spv::Decoration decoration;
8412 // GL_NV_sample_mask_override_coverage extension
8413 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008414 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008415 else
8416 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008417 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008418 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008419 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008420 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8421 }
8422 }
chaoc771d89f2017-01-13 01:10:53 -08008423 else if (builtIn == spv::BuiltInLayer) {
8424 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008425 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008426 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008427 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8428 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8429 }
John Kessenichb41bff62017-08-11 13:07:17 -06008430 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008431 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8432 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008433 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8434 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8435 }
8436 }
8437
chaoc6e5acae2016-12-20 13:28:52 -08008438 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008439 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008440 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008441 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8442 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008443 if (symbol->getQualifier().pervertexNV) {
8444 builder.addDecoration(id, spv::DecorationPerVertexNV);
8445 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8446 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8447 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008448
John Kessenich5d610ee2018-03-07 18:05:55 -07008449 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8450 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8451 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8452 symbol->getType().getQualifier().semanticName);
8453 }
8454
John Kessenich7015bd62019-08-01 03:28:08 -06008455 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008456 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8457 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008458 }
John Kessenichb9197c82019-08-11 07:41:45 -06008459#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008460
John Kessenich140f3df2015-06-26 16:58:36 -06008461 return id;
8462}
8463
John Kessenicha28f7a72019-08-06 07:00:58 -06008464#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008465// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8466void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8467{
8468 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008469 if (qualifier.perPrimitiveNV) {
8470 // Need to add capability/extension for fragment shader.
8471 // Mesh shader already adds this by default.
8472 if (glslangIntermediate->getStage() == EShLangFragment) {
8473 builder.addCapability(spv::CapabilityMeshShadingNV);
8474 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8475 }
Chao Chen3c366992018-09-19 11:41:59 -07008476 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008477 }
Chao Chen3c366992018-09-19 11:41:59 -07008478 if (qualifier.perViewNV)
8479 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8480 if (qualifier.perTaskNV)
8481 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8482 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008483 if (qualifier.perPrimitiveNV) {
8484 // Need to add capability/extension for fragment shader.
8485 // Mesh shader already adds this by default.
8486 if (glslangIntermediate->getStage() == EShLangFragment) {
8487 builder.addCapability(spv::CapabilityMeshShadingNV);
8488 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8489 }
Chao Chen3c366992018-09-19 11:41:59 -07008490 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008491 }
Chao Chen3c366992018-09-19 11:41:59 -07008492 if (qualifier.perViewNV)
8493 builder.addDecoration(id, spv::DecorationPerViewNV);
8494 if (qualifier.perTaskNV)
8495 builder.addDecoration(id, spv::DecorationPerTaskNV);
8496 }
8497}
8498#endif
8499
John Kessenich55e7d112015-11-15 21:33:39 -07008500// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008501// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008502//
8503// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8504//
8505// Recursively walk the nodes. The nodes form a tree whose leaves are
8506// regular constants, which themselves are trees that createSpvConstant()
8507// recursively walks. So, this function walks the "top" of the tree:
8508// - emit specialization constant-building instructions for specConstant
8509// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008510spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008511{
John Kessenich7cc0e282016-03-20 00:46:02 -06008512 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008513
qining4f4bb812016-04-03 23:55:17 -04008514 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008515 if (! node.getQualifier().specConstant) {
8516 // hand off to the non-spec-constant path
8517 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8518 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008519 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8520 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8521 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008522 }
8523
8524 // We now know we have a specialization constant to build
8525
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008526 // Extra capabilities may be needed.
8527 if (node.getType().contains8BitInt())
8528 builder.addCapability(spv::CapabilityInt8);
8529 if (node.getType().contains16BitFloat())
8530 builder.addCapability(spv::CapabilityFloat16);
8531 if (node.getType().contains16BitInt())
8532 builder.addCapability(spv::CapabilityInt16);
8533 if (node.getType().contains64BitInt())
8534 builder.addCapability(spv::CapabilityInt64);
8535 if (node.getType().containsDouble())
8536 builder.addCapability(spv::CapabilityFloat64);
8537
John Kessenichd94c0032016-05-30 19:29:40 -06008538 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008539 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8540 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8541 std::vector<spv::Id> dimConstId;
8542 for (int dim = 0; dim < 3; ++dim) {
8543 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8544 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008545 if (specConst) {
8546 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8547 glslangIntermediate->getLocalSizeSpecId(dim));
8548 }
qining4f4bb812016-04-03 23:55:17 -04008549 }
8550 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8551 }
8552
8553 // An AST node labelled as specialization constant should be a symbol node.
8554 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8555 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008556 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008557 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008558 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8559 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8560 // will set the builder into spec constant op instruction generating mode.
8561 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008562 result = accessChainLoad(sub_tree->getType());
8563 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008564 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008565 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008566 } else {
8567 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008568 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008569 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008570 builder.addName(result, sn->getName().c_str());
8571 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008572 }
qining4f4bb812016-04-03 23:55:17 -04008573
8574 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8575 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008576 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008577 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008578}
8579
John Kessenich140f3df2015-06-26 16:58:36 -06008580// Use 'consts' as the flattened glslang source of scalar constants to recursively
8581// build the aggregate SPIR-V constant.
8582//
8583// If there are not enough elements present in 'consts', 0 will be substituted;
8584// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8585//
John Kessenich8985fc92020-03-03 10:25:07 -07008586spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8587 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008588{
8589 // vector of constants for SPIR-V
8590 std::vector<spv::Id> spvConsts;
8591
8592 // Type is used for struct and array constants
8593 spv::Id typeId = convertGlslangToSpvType(glslangType);
8594
8595 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008596 glslang::TType elementType(glslangType, 0);
8597 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008598 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008599 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008600 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008601 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008602 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008603 } else if (glslangType.isCoopMat()) {
8604 glslang::TType componentType(glslangType.getBasicType());
8605 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008606 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008607 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8608 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008609 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008610 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008611 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8612 bool zero = nextConst >= consts.size();
8613 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008614 case glslang::EbtInt:
8615 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8616 break;
8617 case glslang::EbtUint:
8618 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8619 break;
8620 case glslang::EbtFloat:
8621 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8622 break;
8623 case glslang::EbtBool:
8624 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8625 break;
8626#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008627 case glslang::EbtInt8:
8628 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8629 break;
8630 case glslang::EbtUint8:
8631 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8632 break;
8633 case glslang::EbtInt16:
8634 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8635 break;
8636 case glslang::EbtUint16:
8637 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8638 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008639 case glslang::EbtInt64:
8640 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8641 break;
8642 case glslang::EbtUint64:
8643 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8644 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008645 case glslang::EbtDouble:
8646 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8647 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008648 case glslang::EbtFloat16:
8649 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8650 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008651#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008652 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008653 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008654 break;
8655 }
8656 ++nextConst;
8657 }
8658 } else {
8659 // we have a non-aggregate (scalar) constant
8660 bool zero = nextConst >= consts.size();
8661 spv::Id scalar = 0;
8662 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008663 case glslang::EbtInt:
8664 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8665 break;
8666 case glslang::EbtUint:
8667 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8668 break;
8669 case glslang::EbtFloat:
8670 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8671 break;
8672 case glslang::EbtBool:
8673 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8674 break;
8675#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008676 case glslang::EbtInt8:
8677 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8678 break;
8679 case glslang::EbtUint8:
8680 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8681 break;
8682 case glslang::EbtInt16:
8683 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8684 break;
8685 case glslang::EbtUint16:
8686 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8687 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008688 case glslang::EbtInt64:
8689 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8690 break;
8691 case glslang::EbtUint64:
8692 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8693 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008694 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008695 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008696 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008697 case glslang::EbtFloat16:
8698 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8699 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008700 case glslang::EbtReference:
8701 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8702 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8703 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008704#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008705 case glslang::EbtString:
8706 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8707 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008708 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008709 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008710 break;
8711 }
8712 ++nextConst;
8713 return scalar;
8714 }
8715
8716 return builder.makeCompositeConstant(typeId, spvConsts);
8717}
8718
John Kessenich7c1aa102015-10-15 13:29:11 -06008719// Return true if the node is a constant or symbol whose reading has no
8720// non-trivial observable cost or effect.
8721bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8722{
8723 // don't know what this is
8724 if (node == nullptr)
8725 return false;
8726
8727 // a constant is safe
8728 if (node->getAsConstantUnion() != nullptr)
8729 return true;
8730
8731 // not a symbol means non-trivial
8732 if (node->getAsSymbolNode() == nullptr)
8733 return false;
8734
8735 // a symbol, depends on what's being read
8736 switch (node->getType().getQualifier().storage) {
8737 case glslang::EvqTemporary:
8738 case glslang::EvqGlobal:
8739 case glslang::EvqIn:
8740 case glslang::EvqInOut:
8741 case glslang::EvqConst:
8742 case glslang::EvqConstReadOnly:
8743 case glslang::EvqUniform:
8744 return true;
8745 default:
8746 return false;
8747 }
qining25262b32016-05-06 17:25:16 -04008748}
John Kessenich7c1aa102015-10-15 13:29:11 -06008749
8750// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008751// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008752// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008753// Return true if trivial.
8754bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8755{
8756 if (node == nullptr)
8757 return false;
8758
John Kessenich84cc15f2017-05-24 16:44:47 -06008759 // count non scalars as trivial, as well as anything coming from HLSL
8760 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008761 return true;
8762
John Kessenich7c1aa102015-10-15 13:29:11 -06008763 // symbols and constants are trivial
8764 if (isTrivialLeaf(node))
8765 return true;
8766
8767 // otherwise, it needs to be a simple operation or one or two leaf nodes
8768
8769 // not a simple operation
8770 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8771 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8772 if (binaryNode == nullptr && unaryNode == nullptr)
8773 return false;
8774
8775 // not on leaf nodes
8776 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8777 return false;
8778
8779 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8780 return false;
8781 }
8782
8783 switch (node->getAsOperator()->getOp()) {
8784 case glslang::EOpLogicalNot:
8785 case glslang::EOpConvIntToBool:
8786 case glslang::EOpConvUintToBool:
8787 case glslang::EOpConvFloatToBool:
8788 case glslang::EOpConvDoubleToBool:
8789 case glslang::EOpEqual:
8790 case glslang::EOpNotEqual:
8791 case glslang::EOpLessThan:
8792 case glslang::EOpGreaterThan:
8793 case glslang::EOpLessThanEqual:
8794 case glslang::EOpGreaterThanEqual:
8795 case glslang::EOpIndexDirect:
8796 case glslang::EOpIndexDirectStruct:
8797 case glslang::EOpLogicalXor:
8798 case glslang::EOpAny:
8799 case glslang::EOpAll:
8800 return true;
8801 default:
8802 return false;
8803 }
8804}
8805
8806// Emit short-circuiting code, where 'right' is never evaluated unless
8807// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008808spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8809 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008810{
8811 spv::Id boolTypeId = builder.makeBoolType();
8812
8813 // emit left operand
8814 builder.clearAccessChain();
8815 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008816 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008817
8818 // Operands to accumulate OpPhi operands
8819 std::vector<spv::Id> phiOperands;
8820 // accumulate left operand's phi information
8821 phiOperands.push_back(leftId);
8822 phiOperands.push_back(builder.getBuildPoint()->getId());
8823
8824 // Make the two kinds of operation symmetric with a "!"
8825 // || => emit "if (! left) result = right"
8826 // && => emit "if ( left) result = right"
8827 //
8828 // TODO: this runtime "not" for || could be avoided by adding functionality
8829 // to 'builder' to have an "else" without an "then"
8830 if (op == glslang::EOpLogicalOr)
8831 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8832
8833 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008834 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008835
8836 // emit right operand as the "then" part of the "if"
8837 builder.clearAccessChain();
8838 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008839 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008840
8841 // accumulate left operand's phi information
8842 phiOperands.push_back(rightId);
8843 phiOperands.push_back(builder.getBuildPoint()->getId());
8844
8845 // finish the "if"
8846 ifBuilder.makeEndIf();
8847
8848 // phi together the two results
8849 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8850}
8851
John Kessenicha28f7a72019-08-06 07:00:58 -06008852#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008853// Return type Id of the imported set of extended instructions corresponds to the name.
8854// Import this set if it has not been imported yet.
8855spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8856{
8857 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8858 return extBuiltinMap[name];
8859 else {
Rex Xu51596642016-09-21 18:56:12 +08008860 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008861 spv::Id extBuiltins = builder.import(name);
8862 extBuiltinMap[name] = extBuiltins;
8863 return extBuiltins;
8864 }
8865}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008866#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008867
John Kessenich140f3df2015-06-26 16:58:36 -06008868}; // end anonymous namespace
8869
8870namespace glslang {
8871
John Kessenich68d78fd2015-07-12 19:28:10 -06008872void GetSpirvVersion(std::string& version)
8873{
John Kessenich9e55f632015-07-15 10:03:39 -06008874 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008875 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008876 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008877 version = buf;
8878}
8879
John Kessenicha372a3e2017-11-02 22:32:14 -06008880// For low-order part of the generator's magic number. Bump up
8881// when there is a change in the style (e.g., if SSA form changes,
8882// or a different instruction sequence to do something gets used).
8883int GetSpirvGeneratorVersion()
8884{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008885 // return 1; // start
8886 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008887 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008888 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008889 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008890 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8891 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008892 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008893 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008894 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8895 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008896}
8897
John Kessenich140f3df2015-06-26 16:58:36 -06008898// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008899void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008900{
8901 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008902 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008903 if (out.fail())
8904 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008905 for (int i = 0; i < (int)spirv.size(); ++i) {
8906 unsigned int word = spirv[i];
8907 out.write((const char*)&word, 4);
8908 }
8909 out.close();
8910}
8911
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008912// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008913void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008914{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008915#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008916 std::ofstream out;
8917 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008918 if (out.fail())
8919 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008920 out << "\t// " <<
8921 GetSpirvGeneratorVersion() <<
8922 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8923 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008924 if (varName != nullptr) {
8925 out << "\t #pragma once" << std::endl;
8926 out << "const uint32_t " << varName << "[] = {" << std::endl;
8927 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008928 const int WORDS_PER_LINE = 8;
8929 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8930 out << "\t";
8931 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8932 const unsigned int word = spirv[i + j];
8933 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8934 if (i + j + 1 < (int)spirv.size()) {
8935 out << ",";
8936 }
8937 }
8938 out << std::endl;
8939 }
Flavio15017db2017-02-15 14:29:33 -08008940 if (varName != nullptr) {
8941 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008942 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008943 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008944 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008945#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008946}
8947
John Kessenich140f3df2015-06-26 16:58:36 -06008948//
8949// Set up the glslang traversal
8950//
John Kessenich4e11b612018-08-30 16:56:59 -06008951void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008952{
Lei Zhang17535f72016-05-04 15:55:59 -04008953 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008954 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008955}
8956
John Kessenich4e11b612018-08-30 16:56:59 -06008957void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008958 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008959{
John Kessenich140f3df2015-06-26 16:58:36 -06008960 TIntermNode* root = intermediate.getTreeRoot();
8961
8962 if (root == 0)
8963 return;
8964
John Kessenich4e11b612018-08-30 16:56:59 -06008965 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008966 if (options == nullptr)
8967 options = &defaultOptions;
8968
John Kessenich4e11b612018-08-30 16:56:59 -06008969 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008970
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008971 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008972 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008973 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008974 it.dumpSpv(spirv);
8975
GregFfb03a552018-03-29 11:49:14 -06008976#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008977 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8978 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008979 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008980 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8981 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008982 prelegalization = false;
8983 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008984 else if (options->stripDebugInfo) {
8985 // Strip debug info even if optimization is disabled.
8986 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8987 }
John Kessenich717c80a2018-08-23 15:17:10 -06008988
John Kessenich4e11b612018-08-30 16:56:59 -06008989 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008990 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008991
John Kessenich717c80a2018-08-23 15:17:10 -06008992 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008993 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008994
GregFcd1f1692017-09-21 18:40:22 -06008995#endif
8996
John Kessenich4e11b612018-08-30 16:56:59 -06008997 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008998}
8999
9000}; // end namespace glslang