blob: e0b5a19fedcef151f61e28d00795238c866b3f2a [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&);
193 void visitFunctions(const glslang::TIntermSequence&);
194 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700195 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
196 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600197 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
198 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600199 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
200
John Kessenichead86222018-03-28 18:01:20 -0600201 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
202 glslang::TBasicType typeProxy, bool reduceComparison = true);
203 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
204 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700205 glslang::TBasicType typeProxy,
206 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600207 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
208 glslang::TBasicType typeProxy);
209 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
210 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600211 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600212 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700213 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
214 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
215 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
216 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
217 glslang::TBasicType typeProxy);
218 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
219 spv::Id typeId, std::vector<spv::Id>& operands);
220 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
221 glslang::TBasicType typeProxy);
222 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
223 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800224 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600225 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700226 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400227 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700228 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
229 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600230 bool isTrivialLeaf(const glslang::TIntermTyped* node);
231 bool isTrivial(const glslang::TIntermTyped* node);
232 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800233 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400234 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600235 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500236 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600237
John Kessenich121853f2017-05-31 17:11:16 -0600238 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600240 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700241 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600242 int sequenceDepth;
243
Lei Zhang17535f72016-05-04 15:55:59 -0400244 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400245
John Kessenich140f3df2015-06-26 16:58:36 -0600246 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
247 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700248 bool inEntryPoint;
249 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700250 bool linkageOnly; // true when visiting the set of objects in the AST present only for
251 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700252 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600253 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600254 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600255 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500256 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800257 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600258
John Kessenich2f273362015-07-18 22:34:27 -0600259 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700260 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
261 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600262 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700263 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700264 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800265 std::unordered_map<int, std::vector<int>> memberRemapper;
266 // for mapping glslang symbol struct to symbol Id
267 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600268 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700269 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600270 // Map pointee types for EbtReference to their forward pointers
271 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600272 // Type forcing, for when SPIR-V wants a different type than the AST,
273 // requiring local translation to and from SPIR-V type on every access.
274 // Maps <builtin-variable-id -> AST-required-type-id>
275 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600276};
277
278//
279// Helper functions for translating glslang representations to SPIR-V enumerants.
280//
281
282// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700283spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600284{
John Kessenich155d3512019-08-08 23:29:20 -0600285#ifdef GLSLANG_WEB
286 return spv::SourceLanguageESSL;
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -0400287#elif defined(GLSLANG_ANGLE)
288 return spv::SourceLanguageGLSL;
John Kessenich155d3512019-08-08 23:29:20 -0600289#endif
290
John Kessenich66e2faf2016-03-12 18:34:36 -0700291 switch (source) {
292 case glslang::EShSourceGlsl:
293 switch (profile) {
294 case ENoProfile:
295 case ECoreProfile:
296 case ECompatibilityProfile:
297 return spv::SourceLanguageGLSL;
298 case EEsProfile:
299 return spv::SourceLanguageESSL;
300 default:
301 return spv::SourceLanguageUnknown;
302 }
303 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600304 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
306 return spv::SourceLanguageUnknown;
307 }
308}
309
310// Translate glslang language (stage) to SPIR-V execution model.
311spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
312{
313 switch (stage) {
314 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600315 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600316 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600317#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600318 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
319 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
320 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400321 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
322 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
323 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
324 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
325 case EShLangMiss: return spv::ExecutionModelMissKHR;
326 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700327 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
328 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
329#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600330 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700331 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600332 return spv::ExecutionModelFragment;
333 }
334}
335
John Kessenich140f3df2015-06-26 16:58:36 -0600336// Translate glslang sampler type to SPIR-V dimensionality.
337spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
338{
339 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700340 case glslang::Esd1D: return spv::Dim1D;
341 case glslang::Esd2D: return spv::Dim2D;
342 case glslang::Esd3D: return spv::Dim3D;
343 case glslang::EsdCube: return spv::DimCube;
344 case glslang::EsdRect: return spv::DimRect;
345 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700346 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700348 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600349 return spv::Dim2D;
350 }
351}
352
John Kessenichf6640762016-08-01 19:44:00 -0600353// Translate glslang precision to SPIR-V precision decorations.
354spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600355{
John Kessenichf6640762016-08-01 19:44:00 -0600356 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700357 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600358 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600359 default:
360 return spv::NoPrecision;
361 }
362}
363
John Kessenichf6640762016-08-01 19:44:00 -0600364// Translate glslang type to SPIR-V precision decorations.
365spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
366{
367 return TranslatePrecisionDecoration(type.getQualifier().precision);
368}
369
John Kessenich140f3df2015-06-26 16:58:36 -0600370// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600371spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600372{
373 if (type.getBasicType() == glslang::EbtBlock) {
374 switch (type.getQualifier().storage) {
375 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600376 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::EvqVaryingIn: return spv::DecorationBlock;
378 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600379#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400380 case glslang::EvqPayload: return spv::DecorationBlock;
381 case glslang::EvqPayloadIn: return spv::DecorationBlock;
382 case glslang::EvqHitAttr: return spv::DecorationBlock;
383 case glslang::EvqCallableData: return spv::DecorationBlock;
384 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700385#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600386 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700387 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600388 break;
389 }
390 }
391
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600393}
394
Rex Xu1da878f2016-02-21 20:59:01 +0800395// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700396void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
397 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800398{
Jeff Bolz36831c92018-09-05 10:11:41 -0500399 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600400 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500401 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600402 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500403 memory.push_back(spv::DecorationVolatile);
404 memory.push_back(spv::DecorationCoherent);
405 }
John Kessenich14b85d32018-06-04 15:36:03 -0600406 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600407 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800408 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600409 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800410 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600411 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800412 memory.push_back(spv::DecorationNonReadable);
413}
414
John Kessenich140f3df2015-06-26 16:58:36 -0600415// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700416spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600417{
418 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700419 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600420 case glslang::ElmRowMajor:
421 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700422 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600423 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700424 default:
425 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600426 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600427 }
428 } else {
429 switch (type.getBasicType()) {
430 default:
John Kessenich4016e382016-07-15 11:53:56 -0600431 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600432 break;
433 case glslang::EbtBlock:
434 switch (type.getQualifier().storage) {
435 case glslang::EvqUniform:
436 case glslang::EvqBuffer:
437 switch (type.getQualifier().layoutPacking) {
438 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600439 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
440 default:
John Kessenich4016e382016-07-15 11:53:56 -0600441 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600442 }
443 case glslang::EvqVaryingIn:
444 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700445 if (type.getQualifier().isTaskMemory()) {
446 switch (type.getQualifier().layoutPacking) {
447 case glslang::ElpShared: return spv::DecorationGLSLShared;
448 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
449 default: break;
450 }
451 } else {
452 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
453 }
John Kessenich4016e382016-07-15 11:53:56 -0600454 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600455#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400456 case glslang::EvqPayload:
457 case glslang::EvqPayloadIn:
458 case glslang::EvqHitAttr:
459 case glslang::EvqCallableData:
460 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700461 return spv::DecorationMax;
462#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600463 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700464 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600465 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600466 }
467 }
468 }
469}
470
471// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600472// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700473// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800474spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600475{
Rex Xubbceed72016-05-21 09:40:44 +0800476 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700477 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600478 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600479 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700480 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700481 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600482 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600483 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800484 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800485 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800486 }
Rex Xubbceed72016-05-21 09:40:44 +0800487 else
John Kessenich4016e382016-07-15 11:53:56 -0600488 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800489}
490
491// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600492// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800493// should be applied.
494spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
495{
John Kessenichb9197c82019-08-11 07:41:45 -0600496 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600497 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600498#ifndef GLSLANG_WEB
499 else if (qualifier.patch)
500 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700501 else if (qualifier.sample) {
502 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600503 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600504 }
505#endif
506
507 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600508}
509
John Kessenich92187592016-02-01 13:45:25 -0700510// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700511spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600512{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700513 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600514 return spv::DecorationInvariant;
515 else
John Kessenich4016e382016-07-15 11:53:56 -0600516 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600517}
518
qining9220dbb2016-05-04 17:34:38 -0400519// If glslang type is noContraction, return SPIR-V NoContraction decoration.
520spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
521{
John Kessenichb9197c82019-08-11 07:41:45 -0600522#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600523 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400524 return spv::DecorationNoContraction;
525 else
John Kessenichb9197c82019-08-11 07:41:45 -0600526#endif
John Kessenich4016e382016-07-15 11:53:56 -0600527 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400528}
529
John Kessenich5611c6d2018-04-05 11:25:02 -0600530// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
531spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
532{
John Kessenichb9197c82019-08-11 07:41:45 -0600533#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600534 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600535 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600536 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
537 return spv::DecorationNonUniformEXT;
538 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600539#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600540 return spv::DecorationMax;
541}
542
greg-lunarg639f5462020-11-12 11:10:07 -0700543// If lvalue flags contains nonUniform, return SPIR-V NonUniform decoration.
544spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(
545 const spv::Builder::AccessChain::CoherentFlags& coherentFlags)
546{
547#ifndef GLSLANG_WEB
548 if (coherentFlags.isNonUniform()) {
549 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
550 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
551 return spv::DecorationNonUniformEXT;
552 } else
553#endif
554 return spv::DecorationMax;
555}
556
John Kessenichb9197c82019-08-11 07:41:45 -0600557spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
558 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500559{
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600561
562#ifndef GLSLANG_WEB
563 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
564 return mask;
565
Daniel Kochdb32b242020-03-17 20:42:47 -0400566 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500567 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
568 spv::MemoryAccessMakePointerVisibleKHRMask;
569 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400570
Jeff Bolz36831c92018-09-05 10:11:41 -0500571 if (coherentFlags.nonprivate) {
572 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
573 }
574 if (coherentFlags.volatil) {
575 mask = mask | spv::MemoryAccessVolatileMask;
576 }
577 if (mask != spv::MemoryAccessMaskNone) {
578 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
579 }
John Kessenichb9197c82019-08-11 07:41:45 -0600580#endif
581
Jeff Bolz36831c92018-09-05 10:11:41 -0500582 return mask;
583}
584
John Kessenichb9197c82019-08-11 07:41:45 -0600585spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
586 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500587{
Jeff Bolz36831c92018-09-05 10:11:41 -0500588 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600589
590#ifndef GLSLANG_WEB
591 if (!glslangIntermediate->usingVulkanMemoryModel())
592 return mask;
593
Jeff Bolz36831c92018-09-05 10:11:41 -0500594 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400595 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500596 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
597 spv::ImageOperandsMakeTexelVisibleKHRMask;
598 }
599 if (coherentFlags.nonprivate) {
600 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
601 }
602 if (coherentFlags.volatil) {
603 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
604 }
605 if (mask != spv::ImageOperandsMaskNone) {
606 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
607 }
John Kessenichb9197c82019-08-11 07:41:45 -0600608#endif
609
Jeff Bolz36831c92018-09-05 10:11:41 -0500610 return mask;
611}
612
613spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
614{
John Kessenichb9197c82019-08-11 07:41:45 -0600615 spv::Builder::AccessChain::CoherentFlags flags = {};
616#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500617 flags.coherent = type.getQualifier().coherent;
618 flags.devicecoherent = type.getQualifier().devicecoherent;
619 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
620 // shared variables are implicitly workgroupcoherent in GLSL.
621 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
622 type.getQualifier().storage == glslang::EvqShared;
623 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400624 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600625 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500626 // *coherent variables are implicitly nonprivate in GLSL
627 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400628 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600629 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500630 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600631#endif
greg-lunarg639f5462020-11-12 11:10:07 -0700632 flags.nonUniform = type.getQualifier().nonUniform;
Jeff Bolz36831c92018-09-05 10:11:41 -0500633 return flags;
634}
635
John Kessenichb9197c82019-08-11 07:41:45 -0600636spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
637 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500638{
John Kessenichb9197c82019-08-11 07:41:45 -0600639 spv::Scope scope = spv::ScopeMax;
640
641#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600642 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500643 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
644 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
645 } else if (coherentFlags.devicecoherent) {
646 scope = spv::ScopeDevice;
647 } else if (coherentFlags.queuefamilycoherent) {
648 scope = spv::ScopeQueueFamilyKHR;
649 } else if (coherentFlags.workgroupcoherent) {
650 scope = spv::ScopeWorkgroup;
651 } else if (coherentFlags.subgroupcoherent) {
652 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400653 } else if (coherentFlags.shadercallcoherent) {
654 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500655 }
656 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
657 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
658 }
John Kessenichb9197c82019-08-11 07:41:45 -0600659#endif
660
Jeff Bolz36831c92018-09-05 10:11:41 -0500661 return scope;
662}
663
David Netoa901ffe2016-06-08 14:11:40 +0100664// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
665// associated capabilities when required. For some built-in variables, a capability
666// is generated only when using the variable in an executable instruction, but not when
667// just declaring a struct member variable with it. This is true for PointSize,
668// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700669spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
670 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600671{
672 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700673 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600674#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600675 // Defer adding the capability until the built-in is actually used.
676 if (! memberDeclaration) {
677 switch (glslangIntermediate->getStage()) {
678 case EShLangGeometry:
679 builder.addCapability(spv::CapabilityGeometryPointSize);
680 break;
681 case EShLangTessControl:
682 case EShLangTessEvaluation:
683 builder.addCapability(spv::CapabilityTessellationPointSize);
684 break;
685 default:
686 break;
687 }
John Kessenich92187592016-02-01 13:45:25 -0700688 }
John Kessenich155d3512019-08-08 23:29:20 -0600689#endif
John Kessenich92187592016-02-01 13:45:25 -0700690 return spv::BuiltInPointSize;
691
John Kessenicha28f7a72019-08-06 07:00:58 -0600692 case glslang::EbvPosition: return spv::BuiltInPosition;
693 case glslang::EbvVertexId: return spv::BuiltInVertexId;
694 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
695 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
696 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
697
698 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
699 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
700 case glslang::EbvFace: return spv::BuiltInFrontFacing;
701 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
702
John Kessenich3dd1ce52019-10-17 07:08:40 -0600703 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
704 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
705 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
706 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
707 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
708 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
709
John Kessenicha28f7a72019-08-06 07:00:58 -0600710#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600711 // These *Distance capabilities logically belong here, but if the member is declared and
712 // then never used, consumers of SPIR-V prefer the capability not be declared.
713 // They are now generated when used, rather than here when declared.
714 // Potentially, the specification should be more clear what the minimum
715 // use needed is to trigger the capability.
716 //
John Kessenich92187592016-02-01 13:45:25 -0700717 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100718 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800719 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700720 return spv::BuiltInClipDistance;
721
722 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100723 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800724 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700725 return spv::BuiltInCullDistance;
726
727 case glslang::EbvViewportIndex:
David Netofb53f832020-11-12 15:00:16 -0500728 if (glslangIntermediate->getStage() == EShLangGeometry ||
729 glslangIntermediate->getStage() == EShLangFragment) {
730 builder.addCapability(spv::CapabilityMultiViewport);
731 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600732 if (glslangIntermediate->getStage() == EShLangVertex ||
733 glslangIntermediate->getStage() == EShLangTessControl ||
734 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800735
Sidney Just56350ca2020-11-02 11:27:40 -0800736 if (builder.getSpvVersion() < spv::Spv_1_5) {
737 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
738 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
739 }
740 else
741 builder.addCapability(spv::CapabilityShaderViewportIndex);
Rex Xu5e317ff2017-03-16 23:02:39 +0800742 }
John Kessenich92187592016-02-01 13:45:25 -0700743 return spv::BuiltInViewportIndex;
744
John Kessenich5e801132016-02-15 11:09:46 -0700745 case glslang::EbvSampleId:
746 builder.addCapability(spv::CapabilitySampleRateShading);
747 return spv::BuiltInSampleId;
748
749 case glslang::EbvSamplePosition:
750 builder.addCapability(spv::CapabilitySampleRateShading);
751 return spv::BuiltInSamplePosition;
752
753 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700754 return spv::BuiltInSampleMask;
755
John Kessenich78a45572016-07-08 14:05:15 -0600756 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700757 if (glslangIntermediate->getStage() == EShLangMeshNV) {
758 return spv::BuiltInLayer;
759 }
David Netofb53f832020-11-12 15:00:16 -0500760 if (glslangIntermediate->getStage() == EShLangGeometry ||
761 glslangIntermediate->getStage() == EShLangFragment) {
762 builder.addCapability(spv::CapabilityGeometry);
763 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600764 if (glslangIntermediate->getStage() == EShLangVertex ||
765 glslangIntermediate->getStage() == EShLangTessControl ||
766 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800767
Sidney Just56350ca2020-11-02 11:27:40 -0800768 if (builder.getSpvVersion() < spv::Spv_1_5) {
769 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
770 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
771 } else
772 builder.addCapability(spv::CapabilityShaderLayer);
Rex Xu5e317ff2017-03-16 23:02:39 +0800773 }
John Kessenich78a45572016-07-08 14:05:15 -0600774 return spv::BuiltInLayer;
775
John Kessenichda581a22015-10-14 14:10:30 -0600776 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600777 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800778 builder.addCapability(spv::CapabilityDrawParameters);
779 return spv::BuiltInBaseVertex;
780
John Kessenichda581a22015-10-14 14:10:30 -0600781 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600782 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800783 builder.addCapability(spv::CapabilityDrawParameters);
784 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200785
John Kessenichda581a22015-10-14 14:10:30 -0600786 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600787 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800788 builder.addCapability(spv::CapabilityDrawParameters);
789 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200790
791 case glslang::EbvPrimitiveId:
792 if (glslangIntermediate->getStage() == EShLangFragment)
793 builder.addCapability(spv::CapabilityGeometry);
794 return spv::BuiltInPrimitiveId;
795
Rex Xu37cdcee2017-06-29 17:46:34 +0800796 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800797 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
798 builder.addCapability(spv::CapabilityStencilExportEXT);
799 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800800
Chowa315b562020-07-02 15:50:36 +0800801 case glslang::EbvShadingRateKHR:
802 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
803 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
804 return spv::BuiltInShadingRateKHR;
805
806 case glslang::EbvPrimitiveShadingRateKHR:
807 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
808 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
809 return spv::BuiltInPrimitiveShadingRateKHR;
810
John Kessenich140f3df2015-06-26 16:58:36 -0600811 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600812 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
813 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
814 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
815 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600816 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800817
Rex Xu574ab042016-04-14 16:53:07 +0800818 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800819 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800820 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
821 return spv::BuiltInSubgroupSize;
822
Rex Xu574ab042016-04-14 16:53:07 +0800823 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800824 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800825 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
826 return spv::BuiltInSubgroupLocalInvocationId;
827
Rex Xu574ab042016-04-14 16:53:07 +0800828 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800829 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
830 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600831 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800832
Rex Xu574ab042016-04-14 16:53:07 +0800833 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800834 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
835 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600836 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800837
Rex Xu574ab042016-04-14 16:53:07 +0800838 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800839 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
840 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600841 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800842
Rex Xu574ab042016-04-14 16:53:07 +0800843 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800844 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
845 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600846 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800847
Rex Xu574ab042016-04-14 16:53:07 +0800848 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800849 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
850 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600851 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800852
John Kessenich66011cb2018-03-06 16:12:04 -0700853 case glslang::EbvNumSubgroups:
854 builder.addCapability(spv::CapabilityGroupNonUniform);
855 return spv::BuiltInNumSubgroups;
856
857 case glslang::EbvSubgroupID:
858 builder.addCapability(spv::CapabilityGroupNonUniform);
859 return spv::BuiltInSubgroupId;
860
861 case glslang::EbvSubgroupSize2:
862 builder.addCapability(spv::CapabilityGroupNonUniform);
863 return spv::BuiltInSubgroupSize;
864
865 case glslang::EbvSubgroupInvocation2:
866 builder.addCapability(spv::CapabilityGroupNonUniform);
867 return spv::BuiltInSubgroupLocalInvocationId;
868
869 case glslang::EbvSubgroupEqMask2:
870 builder.addCapability(spv::CapabilityGroupNonUniform);
871 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
872 return spv::BuiltInSubgroupEqMask;
873
874 case glslang::EbvSubgroupGeMask2:
875 builder.addCapability(spv::CapabilityGroupNonUniform);
876 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
877 return spv::BuiltInSubgroupGeMask;
878
879 case glslang::EbvSubgroupGtMask2:
880 builder.addCapability(spv::CapabilityGroupNonUniform);
881 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
882 return spv::BuiltInSubgroupGtMask;
883
884 case glslang::EbvSubgroupLeMask2:
885 builder.addCapability(spv::CapabilityGroupNonUniform);
886 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
887 return spv::BuiltInSubgroupLeMask;
888
889 case glslang::EbvSubgroupLtMask2:
890 builder.addCapability(spv::CapabilityGroupNonUniform);
891 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
892 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600893
Rex Xu17ff3432016-10-14 17:41:45 +0800894 case glslang::EbvBaryCoordNoPersp:
895 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
896 return spv::BuiltInBaryCoordNoPerspAMD;
897
898 case glslang::EbvBaryCoordNoPerspCentroid:
899 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
900 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
901
902 case glslang::EbvBaryCoordNoPerspSample:
903 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
904 return spv::BuiltInBaryCoordNoPerspSampleAMD;
905
906 case glslang::EbvBaryCoordSmooth:
907 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
908 return spv::BuiltInBaryCoordSmoothAMD;
909
910 case glslang::EbvBaryCoordSmoothCentroid:
911 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
912 return spv::BuiltInBaryCoordSmoothCentroidAMD;
913
914 case glslang::EbvBaryCoordSmoothSample:
915 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
916 return spv::BuiltInBaryCoordSmoothSampleAMD;
917
918 case glslang::EbvBaryCoordPullModel:
919 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
920 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800921
John Kessenich6c8aaac2017-02-27 01:20:51 -0700922 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600923 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700924 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700925 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700926
927 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600928 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700929 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700930 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700931
Daniel Koch5154db52018-11-26 10:01:58 -0500932 case glslang::EbvFragSizeEXT:
933 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
934 builder.addCapability(spv::CapabilityFragmentDensityEXT);
935 return spv::BuiltInFragSizeEXT;
936
937 case glslang::EbvFragInvocationCountEXT:
938 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
939 builder.addCapability(spv::CapabilityFragmentDensityEXT);
940 return spv::BuiltInFragInvocationCountEXT;
941
chaoc771d89f2017-01-13 01:10:53 -0800942 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800943 if (!memberDeclaration) {
944 builder.addExtension(spv::E_SPV_NV_viewport_array2);
945 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
946 }
chaoc771d89f2017-01-13 01:10:53 -0800947 return spv::BuiltInViewportMaskNV;
948 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800949 if (!memberDeclaration) {
950 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
951 builder.addCapability(spv::CapabilityShaderStereoViewNV);
952 }
chaoc771d89f2017-01-13 01:10:53 -0800953 return spv::BuiltInSecondaryPositionNV;
954 case glslang::EbvSecondaryViewportMaskNV:
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::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800960 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800961 if (!memberDeclaration) {
962 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
963 builder.addCapability(spv::CapabilityPerViewAttributesNV);
964 }
chaocdf3956c2017-02-14 14:52:34 -0800965 return spv::BuiltInPositionPerViewNV;
966 case glslang::EbvViewportMaskPerViewNV:
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::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700972 case glslang::EbvFragFullyCoveredNV:
973 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
974 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
975 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700976 case glslang::EbvFragmentSizeNV:
977 builder.addExtension(spv::E_SPV_NV_shading_rate);
978 builder.addCapability(spv::CapabilityShadingRateNV);
979 return spv::BuiltInFragmentSizeNV;
980 case glslang::EbvInvocationsPerPixelNV:
981 builder.addExtension(spv::E_SPV_NV_shading_rate);
982 builder.addCapability(spv::CapabilityShadingRateNV);
983 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700984
Daniel Koch593a4e02019-05-27 16:46:31 -0400985 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400986 case glslang::EbvLaunchId:
987 return spv::BuiltInLaunchIdKHR;
988 case glslang::EbvLaunchSize:
989 return spv::BuiltInLaunchSizeKHR;
990 case glslang::EbvWorldRayOrigin:
991 return spv::BuiltInWorldRayOriginKHR;
992 case glslang::EbvWorldRayDirection:
993 return spv::BuiltInWorldRayDirectionKHR;
994 case glslang::EbvObjectRayOrigin:
995 return spv::BuiltInObjectRayOriginKHR;
996 case glslang::EbvObjectRayDirection:
997 return spv::BuiltInObjectRayDirectionKHR;
998 case glslang::EbvRayTmin:
999 return spv::BuiltInRayTminKHR;
1000 case glslang::EbvRayTmax:
1001 return spv::BuiltInRayTmaxKHR;
1002 case glslang::EbvInstanceCustomIndex:
1003 return spv::BuiltInInstanceCustomIndexKHR;
1004 case glslang::EbvHitT:
1005 return spv::BuiltInHitTKHR;
1006 case glslang::EbvHitKind:
1007 return spv::BuiltInHitKindKHR;
1008 case glslang::EbvObjectToWorld:
1009 case glslang::EbvObjectToWorld3x4:
1010 return spv::BuiltInObjectToWorldKHR;
1011 case glslang::EbvWorldToObject:
1012 case glslang::EbvWorldToObject3x4:
1013 return spv::BuiltInWorldToObjectKHR;
1014 case glslang::EbvIncomingRayFlags:
1015 return spv::BuiltInIncomingRayFlagsKHR;
1016 case glslang::EbvGeometryIndex:
1017 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -04001018
1019 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -07001020 case glslang::EbvBaryCoordNV:
1021 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1022 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1023 return spv::BuiltInBaryCoordNV;
1024 case glslang::EbvBaryCoordNoPerspNV:
1025 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1026 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1027 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001028
1029 // mesh shaders
1030 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001031 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001032 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001033 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001034 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001035 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001036 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001037 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001038 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001039 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001040 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001041 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001042 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001043 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001044 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001045 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001046
1047 // sm builtins
1048 case glslang::EbvWarpsPerSM:
1049 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1050 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1051 return spv::BuiltInWarpsPerSMNV;
1052 case glslang::EbvSMCount:
1053 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1054 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1055 return spv::BuiltInSMCountNV;
1056 case glslang::EbvWarpID:
1057 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1058 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1059 return spv::BuiltInWarpIDNV;
1060 case glslang::EbvSMID:
1061 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1062 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1063 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001064#endif
1065
Rex Xu3e783f92017-02-22 16:44:48 +08001066 default:
1067 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001068 }
1069}
1070
Rex Xufc618912015-09-09 16:42:49 +08001071// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001072spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001073{
1074 assert(type.getBasicType() == glslang::EbtSampler);
1075
John Kessenichb9197c82019-08-11 07:41:45 -06001076#ifdef GLSLANG_WEB
1077 return spv::ImageFormatUnknown;
1078#endif
1079
John Kessenich5d0fa972016-02-15 11:57:00 -07001080 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001081 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001082 case glslang::ElfRg32f:
1083 case glslang::ElfRg16f:
1084 case glslang::ElfR11fG11fB10f:
1085 case glslang::ElfR16f:
1086 case glslang::ElfRgba16:
1087 case glslang::ElfRgb10A2:
1088 case glslang::ElfRg16:
1089 case glslang::ElfRg8:
1090 case glslang::ElfR16:
1091 case glslang::ElfR8:
1092 case glslang::ElfRgba16Snorm:
1093 case glslang::ElfRg16Snorm:
1094 case glslang::ElfRg8Snorm:
1095 case glslang::ElfR16Snorm:
1096 case glslang::ElfR8Snorm:
1097
1098 case glslang::ElfRg32i:
1099 case glslang::ElfRg16i:
1100 case glslang::ElfRg8i:
1101 case glslang::ElfR16i:
1102 case glslang::ElfR8i:
1103
1104 case glslang::ElfRgb10a2ui:
1105 case glslang::ElfRg32ui:
1106 case glslang::ElfRg16ui:
1107 case glslang::ElfRg8ui:
1108 case glslang::ElfR16ui:
1109 case glslang::ElfR8ui:
1110 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1111 break;
1112
Tobski8c1a3a02020-11-04 16:24:23 +00001113 case glslang::ElfR64ui:
1114 case glslang::ElfR64i:
1115 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
1116 builder.addCapability(spv::CapabilityInt64ImageEXT);
John Kessenich5d0fa972016-02-15 11:57:00 -07001117 default:
1118 break;
1119 }
1120
1121 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001122 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001123 case glslang::ElfNone: return spv::ImageFormatUnknown;
1124 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1125 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1126 case glslang::ElfR32f: return spv::ImageFormatR32f;
1127 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1128 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1129 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1130 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1131 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1132 case glslang::ElfR16f: return spv::ImageFormatR16f;
1133 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1134 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1135 case glslang::ElfRg16: return spv::ImageFormatRg16;
1136 case glslang::ElfRg8: return spv::ImageFormatRg8;
1137 case glslang::ElfR16: return spv::ImageFormatR16;
1138 case glslang::ElfR8: return spv::ImageFormatR8;
1139 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1140 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1141 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1142 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1143 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1144 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1145 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1146 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1147 case glslang::ElfR32i: return spv::ImageFormatR32i;
1148 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1149 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1150 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1151 case glslang::ElfR16i: return spv::ImageFormatR16i;
1152 case glslang::ElfR8i: return spv::ImageFormatR8i;
1153 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1154 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1155 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1156 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1157 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1158 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1159 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1160 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1161 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1162 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
Tobski8c1a3a02020-11-04 16:24:23 +00001163 case glslang::ElfR64ui: return spv::ImageFormatR64ui;
1164 case glslang::ElfR64i: return spv::ImageFormatR64i;
John Kessenich4016e382016-07-15 11:53:56 -06001165 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001166 }
1167}
1168
John Kessenich8985fc92020-03-03 10:25:07 -07001169spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1170 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001171{
John Kesseniche18fd202018-01-30 11:01:39 -07001172 if (selectionNode.getFlatten())
1173 return spv::SelectionControlFlattenMask;
1174 if (selectionNode.getDontFlatten())
1175 return spv::SelectionControlDontFlattenMask;
1176 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001177}
1178
John Kessenich8985fc92020-03-03 10:25:07 -07001179spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1180 const
steve-lunargf1709e72017-05-02 20:14:50 -06001181{
John Kesseniche18fd202018-01-30 11:01:39 -07001182 if (switchNode.getFlatten())
1183 return spv::SelectionControlFlattenMask;
1184 if (switchNode.getDontFlatten())
1185 return spv::SelectionControlDontFlattenMask;
1186 return spv::SelectionControlMaskNone;
1187}
1188
John Kessenicha2858d92018-01-31 08:11:18 -07001189// return a non-0 dependency if the dependency argument must be set
1190spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001191 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001192{
1193 spv::LoopControlMask control = spv::LoopControlMaskNone;
1194
1195 if (loopNode.getDontUnroll())
1196 control = control | spv::LoopControlDontUnrollMask;
1197 if (loopNode.getUnroll())
1198 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001199 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001200 control = control | spv::LoopControlDependencyInfiniteMask;
1201 else if (loopNode.getLoopDependency() > 0) {
1202 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001203 operands.push_back((unsigned int)loopNode.getLoopDependency());
1204 }
1205 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1206 if (loopNode.getMinIterations() > 0) {
1207 control = control | spv::LoopControlMinIterationsMask;
1208 operands.push_back(loopNode.getMinIterations());
1209 }
1210 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1211 control = control | spv::LoopControlMaxIterationsMask;
1212 operands.push_back(loopNode.getMaxIterations());
1213 }
1214 if (loopNode.getIterationMultiple() > 1) {
1215 control = control | spv::LoopControlIterationMultipleMask;
1216 operands.push_back(loopNode.getIterationMultiple());
1217 }
1218 if (loopNode.getPeelCount() > 0) {
1219 control = control | spv::LoopControlPeelCountMask;
1220 operands.push_back(loopNode.getPeelCount());
1221 }
1222 if (loopNode.getPartialCount() > 0) {
1223 control = control | spv::LoopControlPartialCountMask;
1224 operands.push_back(loopNode.getPartialCount());
1225 }
John Kessenicha2858d92018-01-31 08:11:18 -07001226 }
John Kesseniche18fd202018-01-30 11:01:39 -07001227
1228 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001229}
1230
John Kessenicha5c5fb62017-05-05 05:09:58 -06001231// Translate glslang type to SPIR-V storage class.
1232spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1233{
Torosdagli06c2eee2020-03-19 11:09:57 -04001234 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001235 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001236 if (type.getQualifier().isPipeInput())
1237 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001238 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001239 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001240
1241 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001242 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001243 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001244 return spv::StorageClassAtomicCounter;
1245 if (type.containsOpaque())
1246 return spv::StorageClassUniformConstant;
1247 }
1248
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001249 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001250 type.getQualifier().isShaderRecord()) {
1251 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001252 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001253
John Kessenichbed4e4f2017-09-08 02:38:07 -06001254 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001255 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001256 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001257 }
1258
1259 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001260 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001261 return spv::StorageClassPushConstant;
1262 if (type.getBasicType() == glslang::EbtBlock)
1263 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001264 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001265 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001266
1267 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001268 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1269 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1270 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001271 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001272#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001273 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1274 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1275 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1276 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1277 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001278#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001279 default:
1280 assert(0);
1281 break;
1282 }
1283
1284 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001285}
1286
John Kessenich5611c6d2018-04-05 11:25:02 -06001287// Add capabilities pertaining to how an array is indexed.
1288void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1289 const glslang::TType& indexType)
1290{
John Kessenichb9197c82019-08-11 07:41:45 -06001291#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001292 if (indexType.getQualifier().isNonUniform()) {
1293 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001294 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001295 if (baseType.getBasicType() == glslang::EbtSampler) {
1296 if (baseType.getQualifier().hasAttachment())
1297 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001298 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001299 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001300 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001301 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1302 else if (baseType.isImage())
1303 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1304 else if (baseType.isTexture())
1305 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1306 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1307 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1308 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1309 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1310 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1311 }
1312 } else {
1313 // assume a dynamically uniform index
1314 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001315 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001316 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001317 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001318 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001319 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001320 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001321 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001322 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001323 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001324 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001325 }
1326 }
John Kessenichb9197c82019-08-11 07:41:45 -06001327#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001328}
1329
qining25262b32016-05-06 17:25:16 -04001330// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001331// descriptor set.
1332bool IsDescriptorResource(const glslang::TType& type)
1333{
John Kessenichf7497e22016-03-08 21:36:22 -07001334 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001335 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001336 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001337 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001338 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001339
1340 // non block...
1341 // basically samplerXXX/subpass/sampler/texture are all included
1342 // if they are the global-scope-class, not the function parameter
1343 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001344 if (type.getBasicType() == glslang::EbtSampler ||
1345 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001346 return type.getQualifier().isUniformOrBuffer();
1347
1348 // None of the above.
1349 return false;
1350}
1351
John Kesseniche0b6cad2015-12-24 10:30:13 -07001352void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1353{
1354 if (child.layoutMatrix == glslang::ElmNone)
1355 child.layoutMatrix = parent.layoutMatrix;
1356
1357 if (parent.invariant)
1358 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001359 if (parent.flat)
1360 child.flat = true;
1361 if (parent.centroid)
1362 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001363#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001364 if (parent.nopersp)
1365 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001366 if (parent.explicitInterp)
1367 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001368 if (parent.perPrimitiveNV)
1369 child.perPrimitiveNV = true;
1370 if (parent.perViewNV)
1371 child.perViewNV = true;
1372 if (parent.perTaskNV)
1373 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001374 if (parent.patch)
1375 child.patch = true;
1376 if (parent.sample)
1377 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001378 if (parent.coherent)
1379 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001380 if (parent.devicecoherent)
1381 child.devicecoherent = true;
1382 if (parent.queuefamilycoherent)
1383 child.queuefamilycoherent = true;
1384 if (parent.workgroupcoherent)
1385 child.workgroupcoherent = true;
1386 if (parent.subgroupcoherent)
1387 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001388 if (parent.shadercallcoherent)
1389 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001390 if (parent.nonprivate)
1391 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001392 if (parent.volatil)
1393 child.volatil = true;
1394 if (parent.restrict)
1395 child.restrict = true;
1396 if (parent.readonly)
1397 child.readonly = true;
1398 if (parent.writeonly)
1399 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001400#endif
greg-lunarg639f5462020-11-12 11:10:07 -07001401 if (parent.nonUniform)
1402 child.nonUniform = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001403}
1404
John Kessenichf2b7f332016-09-01 17:05:23 -06001405bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001406{
John Kessenich7b9fa252016-01-21 18:56:57 -07001407 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001408 // - struct members might inherit from a struct declaration
1409 // (note that non-block structs don't explicitly inherit,
1410 // only implicitly, meaning no decoration involved)
1411 // - affect decorations on the struct members
1412 // (note smooth does not, and expecting something like volatile
1413 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001414 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001415 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001416}
1417
John Kessenich140f3df2015-06-26 16:58:36 -06001418//
1419// Implement the TGlslangToSpvTraverser class.
1420//
1421
John Kessenich8985fc92020-03-03 10:25:07 -07001422TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1423 const glslang::TIntermediate* glslangIntermediate,
1424 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1425 TIntermTraverser(true, false, true),
1426 options(options),
1427 shaderEntry(nullptr), currentFunction(nullptr),
1428 sequenceDepth(0), logger(buildLogger),
1429 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1430 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1431 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001432 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1433 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001434{
1435 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1436
1437 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001438 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1439 glslangIntermediate->getVersion());
1440
John Kessenich121853f2017-05-31 17:11:16 -06001441 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001442 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001443 builder.setSourceFile(glslangIntermediate->getSourceFile());
1444
1445 // Set the source shader's text. If for SPV version 1.0, include
1446 // a preamble in comments stating the OpModuleProcessed instructions.
1447 // Otherwise, emit those as actual instructions.
1448 std::string text;
1449 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1450 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001451 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001452 text.append("// OpModuleProcessed ");
1453 text.append(processes[p]);
1454 text.append("\n");
1455 } else
1456 builder.addModuleProcessed(processes[p]);
1457 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001458 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001459 text.append("#line 1\n");
1460 text.append(glslangIntermediate->getSourceText());
1461 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001462 // Pass name and text for all included files
1463 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1464 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1465 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001466 }
John Kessenich140f3df2015-06-26 16:58:36 -06001467 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001468
1469 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1470 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1471
1472 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1473 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001474 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001475 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001476 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001477 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001478 memoryModel = spv::MemoryModelVulkanKHR;
1479 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001480 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001481 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001482 builder.setMemoryModel(addressingModel, memoryModel);
1483
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001484 if (glslangIntermediate->usingVariablePointers()) {
1485 builder.addCapability(spv::CapabilityVariablePointers);
1486 }
1487
John Kessenicheee9d532016-09-19 18:09:30 -06001488 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1489 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001490
1491 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001492 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1493 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001494 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001495
1496 // Add the top-level modes for this shader.
1497
John Kessenich92187592016-02-01 13:45:25 -07001498 if (glslangIntermediate->getXfbMode()) {
1499 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001500 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001501 }
John Kessenich140f3df2015-06-26 16:58:36 -06001502
alelenv59216d52020-05-21 04:38:41 -07001503 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001504 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1505 }
1506
John Kessenich140f3df2015-06-26 16:58:36 -06001507 unsigned int mode;
1508 switch (glslangIntermediate->getStage()) {
1509 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001510 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001511 break;
1512
John Kessenicha28f7a72019-08-06 07:00:58 -06001513 case EShLangFragment:
1514 builder.addCapability(spv::CapabilityShader);
1515 if (glslangIntermediate->getPixelCenterInteger())
1516 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1517
1518 if (glslangIntermediate->getOriginUpperLeft())
1519 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1520 else
1521 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1522
1523 if (glslangIntermediate->getEarlyFragmentTests())
1524 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1525
1526 if (glslangIntermediate->getPostDepthCoverage()) {
1527 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1528 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1529 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1530 }
1531
John Kessenichb9197c82019-08-11 07:41:45 -06001532 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1533 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1534
1535#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001536
John Kessenicha28f7a72019-08-06 07:00:58 -06001537 switch(glslangIntermediate->getDepth()) {
1538 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1539 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1540 default: mode = spv::ExecutionModeMax; break;
1541 }
1542 if (mode != spv::ExecutionModeMax)
1543 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001544 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001545 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1546 break;
1547 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1548 break;
1549 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1550 break;
1551 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1552 break;
1553 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1554 break;
1555 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1556 break;
1557 default: mode = spv::ExecutionModeMax;
1558 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001559 }
1560 if (mode != spv::ExecutionModeMax) {
1561 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1562 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1563 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1564 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1565 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1566 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1567 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1568 } else {
1569 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1570 }
1571 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1572 }
John Kessenichb9197c82019-08-11 07:41:45 -06001573#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001574 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001575
John Kessenicha28f7a72019-08-06 07:00:58 -06001576 case EShLangCompute:
1577 builder.addCapability(spv::CapabilityShader);
1578 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1579 glslangIntermediate->getLocalSize(1),
1580 glslangIntermediate->getLocalSize(2));
1581 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1582 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1583 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1584 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1585 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1586 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1587 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1588 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1589 }
1590 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001591#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001592 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001593 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001594 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001595
steve-lunarge7412492017-03-23 11:56:07 -06001596 glslang::TLayoutGeometry primitive;
1597
1598 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001599 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1600 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001601 primitive = glslangIntermediate->getOutputPrimitive();
1602 } else {
1603 primitive = glslangIntermediate->getInputPrimitive();
1604 }
1605
1606 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001607 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1608 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1609 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001610 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001611 }
John Kessenich4016e382016-07-15 11:53:56 -06001612 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001613 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1614
John Kesseniche6903322015-10-13 16:29:02 -06001615 switch (glslangIntermediate->getVertexSpacing()) {
1616 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1617 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1618 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001619 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001620 }
John Kessenich4016e382016-07-15 11:53:56 -06001621 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001622 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1623
1624 switch (glslangIntermediate->getVertexOrder()) {
1625 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1626 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001627 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001628 }
John Kessenich4016e382016-07-15 11:53:56 -06001629 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001630 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1631
1632 if (glslangIntermediate->getPointMode())
1633 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001634 break;
1635
1636 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001637 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001638 switch (glslangIntermediate->getInputPrimitive()) {
1639 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1640 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1641 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001642 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001643 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001644 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001645 }
John Kessenich4016e382016-07-15 11:53:56 -06001646 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001647 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001648
John Kessenich140f3df2015-06-26 16:58:36 -06001649 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1650
1651 switch (glslangIntermediate->getOutputPrimitive()) {
1652 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1653 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1654 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001655 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001656 }
John Kessenich4016e382016-07-15 11:53:56 -06001657 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001658 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1659 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1660 break;
1661
Daniel Kochdb32b242020-03-17 20:42:47 -04001662 case EShLangRayGen:
1663 case EShLangIntersect:
1664 case EShLangAnyHit:
1665 case EShLangClosestHit:
1666 case EShLangMiss:
1667 case EShLangCallable:
1668 {
1669 auto& extensions = glslangIntermediate->getRequestedExtensions();
1670 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1671 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1672 builder.addExtension("SPV_KHR_ray_tracing");
1673 }
1674 else {
1675 builder.addCapability(spv::CapabilityRayTracingNV);
1676 builder.addExtension("SPV_NV_ray_tracing");
1677 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001678 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001679 }
Chao Chen3c366992018-09-19 11:41:59 -07001680 case EShLangTaskNV:
1681 case EShLangMeshNV:
1682 builder.addCapability(spv::CapabilityMeshShadingNV);
1683 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1684 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1685 glslangIntermediate->getLocalSize(1),
1686 glslangIntermediate->getLocalSize(2));
1687 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001688 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1689 glslangIntermediate->getVertices());
1690 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1691 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001692
1693 switch (glslangIntermediate->getOutputPrimitive()) {
1694 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1695 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1696 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1697 default: mode = spv::ExecutionModeMax; break;
1698 }
1699 if (mode != spv::ExecutionModeMax)
1700 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1701 }
1702 break;
1703#endif
1704
John Kessenich140f3df2015-06-26 16:58:36 -06001705 default:
1706 break;
1707 }
John Kessenich140f3df2015-06-26 16:58:36 -06001708}
1709
John Kessenichfca82622016-11-26 13:23:20 -07001710// Finish creating SPV, after the traversal is complete.
1711void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001712{
John Kessenichf04c51b2018-08-03 15:56:12 -06001713 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001714 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001715 builder.setBuildPoint(shaderEntry->getLastBlock());
1716 builder.leaveFunction();
1717 }
1718
John Kessenich7ba63412015-12-20 17:37:07 -07001719 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001720 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1721 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001722
David Neto8c3d5b42019-10-21 14:50:31 -04001723 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001724 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001725 // Note: WebGPU code generation must have the opportunity to aggressively
1726 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001727 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001728}
1729
John Kessenichfca82622016-11-26 13:23:20 -07001730// Write the SPV into 'out'.
1731void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001732{
John Kessenichfca82622016-11-26 13:23:20 -07001733 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001734}
1735
1736//
1737// Implement the traversal functions.
1738//
1739// Return true from interior nodes to have the external traversal
1740// continue on to children. Return false if children were
1741// already processed.
1742//
1743
1744//
qining25262b32016-05-06 17:25:16 -04001745// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001746// - uniform/input reads
1747// - output writes
1748// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1749// - something simple that degenerates into the last bullet
1750//
1751void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1752{
qining75d1d802016-04-06 14:42:01 -04001753 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001754 if (symbol->getType().isStruct())
1755 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1756
qining75d1d802016-04-06 14:42:01 -04001757 if (symbol->getType().getQualifier().isSpecConstant())
1758 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1759
Rex Xuf6e0fe82020-10-23 22:54:35 +08001760#ifdef ENABLE_HLSL
1761 // Skip symbol handling if it is string-typed
1762 if (symbol->getBasicType() == glslang::EbtString)
1763 return;
1764#endif
1765
John Kessenich140f3df2015-06-26 16:58:36 -06001766 // getSymbolId() will set up all the IO decorations on the first call.
1767 // Formal function parameters were mapped during makeFunctions().
1768 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001769
John Kessenich7ba63412015-12-20 17:37:07 -07001770 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001771 if (!symbol->getType().getQualifier().isParamInput() &&
1772 !symbol->getType().getQualifier().isParamOutput()) {
1773 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1774 // Consider adding to the OpEntryPoint interface list.
1775 // Only looking at structures if they have at least one member.
1776 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1777 spv::StorageClass sc = builder.getStorageClass(id);
1778 // Before SPIR-V 1.4, we only want to include Input and Output.
1779 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001780 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001781 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1782 iOSet.insert(id);
1783 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001784 }
John Kessenich5f77d862017-09-19 11:09:59 -06001785 }
John Kessenich9c14f772019-06-17 08:38:35 -06001786
Daniel Kochdb32b242020-03-17 20:42:47 -04001787 // If the SPIR-V type is required to be different than the AST type
1788 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001789 // translate now from the SPIR-V type to the AST type, for the consuming
1790 // operation.
1791 // Note this turns it from an l-value to an r-value.
1792 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1793 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1794 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001795 }
1796
1797 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001798 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001799 // Prepare to generate code for the access
1800
1801 // L-value chains will be computed left to right. We're on the symbol now,
1802 // which is the left-most part of the access chain, so now is "clear" time,
1803 // followed by setting the base.
1804 builder.clearAccessChain();
1805
1806 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001807 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001808 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001809 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001810 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001811 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001812 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001813 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001814 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1815 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001816 builder.setAccessChainRValue(id);
1817 else
1818 builder.setAccessChainLValue(id);
1819 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001820
John Kessenichb9197c82019-08-11 07:41:45 -06001821#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001822 // Process linkage-only nodes for any special additional interface work.
1823 if (linkageOnly) {
1824 if (glslangIntermediate->getHlslFunctionality1()) {
1825 // Map implicit counter buffers to their originating buffers, which should have been
1826 // seen by now, given earlier pruning of unused counters, and preservation of order
1827 // of declaration.
1828 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1829 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1830 // Save possible originating buffers for counter buffers, keyed by
1831 // making the potential counter-buffer name.
1832 std::string keyName = symbol->getName().c_str();
1833 keyName = glslangIntermediate->addCounterBufferName(keyName);
1834 counterOriginator[keyName] = symbol;
1835 } else {
1836 // Handle a counter buffer, by finding the saved originating buffer.
1837 std::string keyName = symbol->getName().c_str();
1838 auto it = counterOriginator.find(keyName);
1839 if (it != counterOriginator.end()) {
1840 id = getSymbolId(it->second);
1841 if (id != spv::NoResult) {
1842 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001843 if (counterId != spv::NoResult) {
1844 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001845 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001846 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001847 }
1848 }
1849 }
1850 }
1851 }
1852 }
John Kessenich155d3512019-08-08 23:29:20 -06001853#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001854}
1855
1856bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1857{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001858 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001859 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1860 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1861 }
1862 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1863 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1864 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001865
qining40887662016-04-03 22:20:42 -04001866 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1867 if (node->getType().getQualifier().isSpecConstant())
1868 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1869
John Kessenich140f3df2015-06-26 16:58:36 -06001870 // First, handle special cases
1871 switch (node->getOp()) {
1872 case glslang::EOpAssign:
1873 case glslang::EOpAddAssign:
1874 case glslang::EOpSubAssign:
1875 case glslang::EOpMulAssign:
1876 case glslang::EOpVectorTimesMatrixAssign:
1877 case glslang::EOpVectorTimesScalarAssign:
1878 case glslang::EOpMatrixTimesScalarAssign:
1879 case glslang::EOpMatrixTimesMatrixAssign:
1880 case glslang::EOpDivAssign:
1881 case glslang::EOpModAssign:
1882 case glslang::EOpAndAssign:
1883 case glslang::EOpInclusiveOrAssign:
1884 case glslang::EOpExclusiveOrAssign:
1885 case glslang::EOpLeftShiftAssign:
1886 case glslang::EOpRightShiftAssign:
1887 // A bin-op assign "a += b" means the same thing as "a = a + b"
1888 // where a is evaluated before b. For a simple assignment, GLSL
1889 // says to evaluate the left before the right. So, always, left
1890 // node then right node.
1891 {
1892 // get the left l-value, save it away
1893 builder.clearAccessChain();
1894 node->getLeft()->traverse(this);
1895 spv::Builder::AccessChain lValue = builder.getAccessChain();
1896
1897 // evaluate the right
1898 builder.clearAccessChain();
1899 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001900 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001901
1902 if (node->getOp() != glslang::EOpAssign) {
1903 // the left is also an r-value
1904 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001905 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001906
1907 // do the operation
greg-lunarg639f5462020-11-12 11:10:07 -07001908 spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
1909 coherentFlags |= TranslateCoherent(node->getRight()->getType());
John Kessenichead86222018-03-28 18:01:20 -06001910 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001911 TranslateNoContractionDecoration(node->getType().getQualifier()),
greg-lunarg639f5462020-11-12 11:10:07 -07001912 TranslateNonUniformDecoration(coherentFlags) };
John Kessenichead86222018-03-28 18:01:20 -06001913 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001914 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1915 node->getType().getBasicType());
1916
1917 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001918 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001919 }
1920
1921 // store the result
1922 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001923 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001924
1925 // assignments are expressions having an rValue after they are evaluated...
1926 builder.clearAccessChain();
1927 builder.setAccessChainRValue(rValue);
1928 }
1929 return false;
1930 case glslang::EOpIndexDirect:
1931 case glslang::EOpIndexDirectStruct:
1932 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001933 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001934 // Get the left part of the access chain.
1935 node->getLeft()->traverse(this);
1936
1937 // Add the next element in the chain
1938
David Netoa901ffe2016-06-08 14:11:40 +01001939 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001940 if (! node->getLeft()->getType().isArray() &&
1941 node->getLeft()->getType().isVector() &&
1942 node->getOp() == glslang::EOpIndexDirect) {
greg-lunarg639f5462020-11-12 11:10:07 -07001943 // Swizzle is uniform so propagate uniform into access chain
1944 spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
1945 coherentFlags.nonUniform = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06001946 // This is essentially a hard-coded vector swizzle of size 1,
1947 // so short circuit the access-chain stuff with a swizzle.
1948 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001949 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001950 int dummySize;
1951 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
greg-lunarg639f5462020-11-12 11:10:07 -07001952 coherentFlags,
John Kessenich8985fc92020-03-03 10:25:07 -07001953 glslangIntermediate->getBaseAlignmentScalar(
1954 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001955 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001956
1957 // Load through a block reference is performed with a dot operator that
1958 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1959 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001960 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001961 !node->getLeft()->getType().isArray() &&
1962 node->getOp() == glslang::EOpIndexDirectStruct)
1963 {
1964 spv::Id left = accessChainLoad(node->getLeft()->getType());
1965 builder.clearAccessChain();
1966 builder.setAccessChainLValue(left);
1967 }
1968
David Netoa901ffe2016-06-08 14:11:40 +01001969 int spvIndex = glslangIndex;
1970 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1971 node->getOp() == glslang::EOpIndexDirectStruct)
1972 {
1973 // This may be, e.g., an anonymous block-member selection, which generally need
1974 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001975 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1976 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1977 std::vector<int>& remapper = memberRemapper[glslangId];
1978 assert(remapper.size() > 0);
1979 spvIndex = remapper[glslangIndex];
1980 }
David Netoa901ffe2016-06-08 14:11:40 +01001981 }
John Kessenichebb50532016-05-16 19:22:05 -06001982
greg-lunarg639f5462020-11-12 11:10:07 -07001983 // Struct reference propagates uniform lvalue
1984 spv::Builder::AccessChain::CoherentFlags coherentFlags =
1985 TranslateCoherent(node->getLeft()->getType());
1986 coherentFlags.nonUniform = 0;
1987
David Netoa901ffe2016-06-08 14:11:40 +01001988 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001989 builder.accessChainPush(builder.makeIntConstant(spvIndex),
greg-lunarg639f5462020-11-12 11:10:07 -07001990 coherentFlags,
John Kessenich8985fc92020-03-03 10:25:07 -07001991 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001992
1993 // Add capabilities here for accessing PointSize and clip/cull distance.
1994 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001995 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001996 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001997 }
1998 }
1999 return false;
2000 case glslang::EOpIndexIndirect:
2001 {
John Kessenich61a5ce12019-02-07 08:04:12 -07002002 // Array, matrix, or vector indirection with variable index.
2003 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06002004 // matrices are arrays of vectors, so will also work for a matrix.
2005 // Will use the access chain's 'component' for variable index into a vector.
2006
2007 // This adapter is building access chains left to right.
2008 // Set up the access chain to the left.
2009 node->getLeft()->traverse(this);
2010
2011 // save it so that computing the right side doesn't trash it
2012 spv::Builder::AccessChain partial = builder.getAccessChain();
2013
2014 // compute the next index in the chain
2015 builder.clearAccessChain();
2016 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002017 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002018
John Kessenich5611c6d2018-04-05 11:25:02 -06002019 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
2020
John Kessenich140f3df2015-06-26 16:58:36 -06002021 // restore the saved access chain
2022 builder.setAccessChain(partial);
2023
greg-lunarg639f5462020-11-12 11:10:07 -07002024 // Only if index is nonUniform should we propagate nonUniform into access chain
2025 spv::Builder::AccessChain::CoherentFlags index_flags = TranslateCoherent(node->getRight()->getType());
2026 spv::Builder::AccessChain::CoherentFlags coherent_flags = TranslateCoherent(node->getLeft()->getType());
2027 coherent_flags.nonUniform = index_flags.nonUniform;
2028
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002029 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
2030 int dummySize;
greg-lunarg639f5462020-11-12 11:10:07 -07002031 builder.accessChainPushComponent(
2032 index, convertGlslangToSpvType(node->getLeft()->getType()), coherent_flags,
John Kessenich8985fc92020-03-03 10:25:07 -07002033 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2034 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002035 } else
greg-lunarg639f5462020-11-12 11:10:07 -07002036 builder.accessChainPush(index, coherent_flags,
2037 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06002038 }
2039 return false;
2040 case glslang::EOpVectorSwizzle:
2041 {
2042 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002043 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06002044 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002045 int dummySize;
2046 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
2047 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07002048 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2049 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06002050 }
2051 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07002052 case glslang::EOpMatrixSwizzle:
2053 logger->missingFunctionality("matrix swizzle");
2054 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06002055 case glslang::EOpLogicalOr:
2056 case glslang::EOpLogicalAnd:
2057 {
2058
2059 // These may require short circuiting, but can sometimes be done as straight
2060 // binary operations. The right operand must be short circuited if it has
2061 // side effects, and should probably be if it is complex.
2062 if (isTrivial(node->getRight()->getAsTyped()))
2063 break; // handle below as a normal binary operation
2064 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07002065 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
2066 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06002067 builder.clearAccessChain();
2068 builder.setAccessChainRValue(result);
2069 }
2070 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002071 default:
2072 break;
2073 }
2074
2075 // Assume generic binary op...
2076
John Kessenich32cfd492016-02-02 12:37:46 -07002077 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002078 builder.clearAccessChain();
2079 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002080 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002081
John Kessenich32cfd492016-02-02 12:37:46 -07002082 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002083 builder.clearAccessChain();
2084 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002085 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002086
John Kessenich32cfd492016-02-02 12:37:46 -07002087 // get result
John Kessenichead86222018-03-28 18:01:20 -06002088 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002089 TranslateNoContractionDecoration(node->getType().getQualifier()),
2090 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002091 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002092 convertGlslangToSpvType(node->getType()), left, right,
2093 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002094
John Kessenich50e57562015-12-21 21:21:11 -07002095 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002096 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002097 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002098 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002099 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002100 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002101 return false;
2102 }
John Kessenich140f3df2015-06-26 16:58:36 -06002103}
2104
John Kessenich9c14f772019-06-17 08:38:35 -06002105// Figure out what, if any, type changes are needed when accessing a specific built-in.
2106// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2107// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002108std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002109 const glslang::TType& glslangType)
2110{
Daniel Kochdb32b242020-03-17 20:42:47 -04002111 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002112 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002113 case glslang::EbvSubGroupEqMask:
2114 case glslang::EbvSubGroupGeMask:
2115 case glslang::EbvSubGroupGtMask:
2116 case glslang::EbvSubGroupLeMask:
2117 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002118 // these require changing a 64-bit scaler -> a vector of 32-bit components
2119 if (glslangType.isVector())
2120 break;
2121 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2122 builder.makeUintType(64));
2123 return ret;
2124 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002125 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2126 // builtins. During visitBinary we insert a transpose
2127 case glslang::EbvWorldToObject3x4:
2128 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002129 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2130 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2131 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002132 return ret;
2133 }
John Kessenich9c14f772019-06-17 08:38:35 -06002134 default:
2135 break;
2136 }
2137
2138 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2139 return ret;
2140}
2141
2142// For an object previously identified (see getForcedType() and forceType)
2143// as needing type translations, do the translation needed for a load, turning
2144// an L-value into in R-value.
2145spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2146{
2147 const auto forceIt = forceType.find(object);
2148 if (forceIt == forceType.end())
2149 return object;
2150
2151 spv::Id desiredTypeId = forceIt->second;
2152 spv::Id objectTypeId = builder.getTypeId(object);
2153 assert(builder.isPointerType(objectTypeId));
2154 objectTypeId = builder.getContainedTypeId(objectTypeId);
2155 if (builder.isVectorType(objectTypeId) &&
2156 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2157 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2158 // handle 32-bit v.xy* -> 64-bit
2159 builder.clearAccessChain();
2160 builder.setAccessChainLValue(object);
greg-lunarg639f5462020-11-12 11:10:07 -07002161 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
John Kessenich9c14f772019-06-17 08:38:35 -06002162 std::vector<spv::Id> components;
2163 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2164 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2165
2166 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2167 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2168 builder.createCompositeConstruct(vecType, components));
2169 } else {
2170 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2171 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002172 } else if (builder.isMatrixType(objectTypeId)) {
2173 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2174 // and we insert a transpose after loading the original non-transposed builtins
2175 builder.clearAccessChain();
2176 builder.setAccessChainLValue(object);
greg-lunarg639f5462020-11-12 11:10:07 -07002177 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
Daniel Kochdb32b242020-03-17 20:42:47 -04002178 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2179
2180 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002181 logger->missingFunctionality("forcing non 32-bit vector type");
2182 }
2183
2184 return object;
2185}
2186
John Kessenich140f3df2015-06-26 16:58:36 -06002187bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2188{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002189 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002190
qining40887662016-04-03 22:20:42 -04002191 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2192 if (node->getType().getQualifier().isSpecConstant())
2193 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2194
John Kessenichfc51d282015-08-19 13:34:18 -06002195 spv::Id result = spv::NoResult;
2196
2197 // try texturing first
2198 result = createImageTextureFunctionCall(node);
2199 if (result != spv::NoResult) {
2200 builder.clearAccessChain();
2201 builder.setAccessChainRValue(result);
2202
2203 return false; // done with this node
2204 }
2205
2206 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002207
2208 if (node->getOp() == glslang::EOpArrayLength) {
2209 // Quite special; won't want to evaluate the operand.
2210
John Kessenich5611c6d2018-04-05 11:25:02 -06002211 // Currently, the front-end does not allow .length() on an array until it is sized,
2212 // except for the last block membeor of an SSBO.
2213 // TODO: If this changes, link-time sized arrays might show up here, and need their
2214 // size extracted.
2215
John Kessenichc9a80832015-09-12 12:17:44 -06002216 // Normal .length() would have been constant folded by the front-end.
2217 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002218 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002219
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002220 spv::Id length;
2221 if (node->getOperand()->getType().isCoopMat()) {
2222 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2223
2224 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2225 assert(builder.isCooperativeMatrixType(typeId));
2226
2227 length = builder.createCooperativeMatrixLength(typeId);
2228 } else {
2229 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2230 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002231 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2232 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002233 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2234 }
John Kessenichc9a80832015-09-12 12:17:44 -06002235
John Kessenich8c869672018-11-28 07:01:37 -07002236 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2237 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2238 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002239 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2240 if (builder.isInSpecConstCodeGenMode()) {
2241 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2242 } else {
2243 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2244 }
2245 }
John Kessenich8c869672018-11-28 07:01:37 -07002246
John Kessenichc9a80832015-09-12 12:17:44 -06002247 builder.clearAccessChain();
2248 builder.setAccessChainRValue(length);
2249
2250 return false;
2251 }
2252
John Kessenichfc51d282015-08-19 13:34:18 -06002253 // Start by evaluating the operand
2254
John Kessenich8c8505c2016-07-26 12:50:38 -06002255 // Does it need a swizzle inversion? If so, evaluation is inverted;
2256 // operate first on the swizzle base, then apply the swizzle.
2257 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002258 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2259 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002260 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2261 invertedType = getInvertedSwizzleType(*node->getOperand());
2262
John Kessenich140f3df2015-06-26 16:58:36 -06002263 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002264 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002265 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002266 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002267 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002268 operandNode = node->getOperand();
2269
2270 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002271
Rex Xufc618912015-09-09 16:42:49 +08002272 spv::Id operand = spv::NoResult;
2273
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002274 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2275
John Kessenichfb4f2332019-08-09 03:49:15 -06002276#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002277 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2278 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002279 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002280 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2281 node->getOp() == glslang::EOpRayQueryProceed ||
2282 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2283 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2284 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2285 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2286 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2287 node->getOp() == glslang::EOpRayQueryTerminate ||
2288 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002289 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002290 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2291 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2292 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002293#endif
2294 {
John Kessenich32cfd492016-02-02 12:37:46 -07002295 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002296 }
John Kessenich140f3df2015-06-26 16:58:36 -06002297
John Kessenichead86222018-03-28 18:01:20 -06002298 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002299 TranslateNoContractionDecoration(node->getType().getQualifier()),
2300 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002301
2302 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002303 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002304 result = createConversion(node->getOp(), decorations, resultType(), operand,
2305 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002306
2307 // if not, then possibly an operation
2308 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002309 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2310 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002311
2312 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002313 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002314 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002315 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002316 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002317
John Kessenich140f3df2015-06-26 16:58:36 -06002318 builder.clearAccessChain();
2319 builder.setAccessChainRValue(result);
2320
2321 return false; // done with this node
2322 }
2323
2324 // it must be a special case, check...
2325 switch (node->getOp()) {
2326 case glslang::EOpPostIncrement:
2327 case glslang::EOpPostDecrement:
2328 case glslang::EOpPreIncrement:
2329 case glslang::EOpPreDecrement:
2330 {
2331 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002332 spv::Id one = 0;
2333 if (node->getBasicType() == glslang::EbtFloat)
2334 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002335#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002336 else if (node->getBasicType() == glslang::EbtDouble)
2337 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002338 else if (node->getBasicType() == glslang::EbtFloat16)
2339 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002340 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2341 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002342 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2343 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002344 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2345 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002346#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002347 else
2348 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002349 glslang::TOperator op;
2350 if (node->getOp() == glslang::EOpPreIncrement ||
2351 node->getOp() == glslang::EOpPostIncrement)
2352 op = glslang::EOpAdd;
2353 else
2354 op = glslang::EOpSub;
2355
John Kessenichead86222018-03-28 18:01:20 -06002356 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002357 convertGlslangToSpvType(node->getType()), operand, one,
2358 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002359 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002360
2361 // The result of operation is always stored, but conditionally the
2362 // consumed result. The consumed result is always an r-value.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002363 builder.accessChainStore(result,
greg-lunarg639f5462020-11-12 11:10:07 -07002364 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags));
John Kessenich140f3df2015-06-26 16:58:36 -06002365 builder.clearAccessChain();
2366 if (node->getOp() == glslang::EOpPreIncrement ||
2367 node->getOp() == glslang::EOpPreDecrement)
2368 builder.setAccessChainRValue(result);
2369 else
2370 builder.setAccessChainRValue(operand);
2371 }
2372
2373 return false;
2374
John Kessenich155d3512019-08-08 23:29:20 -06002375#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002376 case glslang::EOpEmitStreamVertex:
2377 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2378 return false;
2379 case glslang::EOpEndStreamPrimitive:
2380 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2381 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002382 case glslang::EOpRayQueryTerminate:
2383 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2384 return false;
2385 case glslang::EOpRayQueryConfirmIntersection:
2386 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2387 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002388#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002389
2390 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002391 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002392 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002393 }
John Kessenich140f3df2015-06-26 16:58:36 -06002394}
2395
Jeff Bolz53134492019-06-25 13:31:10 -05002396// Construct a composite object, recursively copying members if their types don't match
2397spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2398{
2399 for (int c = 0; c < (int)constituents.size(); ++c) {
2400 spv::Id& constituent = constituents[c];
2401 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2402 spv::Id rType = builder.getTypeId(constituent);
2403 if (lType != rType) {
2404 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2405 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2406 } else if (builder.isStructType(rType)) {
2407 std::vector<spv::Id> rTypeConstituents;
2408 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2409 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002410 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2411 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002412 }
2413 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2414 } else {
2415 assert(builder.isArrayType(rType));
2416 std::vector<spv::Id> rTypeConstituents;
2417 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2418
2419 spv::Id elementRType = builder.getContainedTypeId(rType);
2420 for (int i = 0; i < numrTypeConstituents; ++i) {
2421 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2422 }
2423 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2424 }
2425 }
2426 }
2427 return builder.createCompositeConstruct(resultTypeId, constituents);
2428}
2429
John Kessenich140f3df2015-06-26 16:58:36 -06002430bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2431{
qining27e04a02016-04-14 16:40:20 -04002432 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2433 if (node->getType().getQualifier().isSpecConstant())
2434 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2435
John Kessenichfc51d282015-08-19 13:34:18 -06002436 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002437 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2438 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2439 // SPIR-V, for an out parameter
2440 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002441
John Kessenich8985fc92020-03-03 10:25:07 -07002442 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2443 invertedType :
2444 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002445
2446 // try texturing
2447 result = createImageTextureFunctionCall(node);
2448 if (result != spv::NoResult) {
2449 builder.clearAccessChain();
2450 builder.setAccessChainRValue(result);
2451
2452 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002453 }
2454#ifndef GLSLANG_WEB
2455 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002456 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002457 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002458 // "imageStore" is a special case, which has no result
2459 return false;
2460 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002461#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002462
John Kessenich140f3df2015-06-26 16:58:36 -06002463 glslang::TOperator binOp = glslang::EOpNull;
2464 bool reduceComparison = true;
2465 bool isMatrix = false;
2466 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002467 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002468
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002469 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2470
John Kessenich140f3df2015-06-26 16:58:36 -06002471 assert(node->getOp());
2472
John Kessenichf6640762016-08-01 19:44:00 -06002473 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002474
2475 switch (node->getOp()) {
2476 case glslang::EOpSequence:
2477 {
2478 if (preVisit)
2479 ++sequenceDepth;
2480 else
2481 --sequenceDepth;
2482
2483 if (sequenceDepth == 1) {
2484 // If this is the parent node of all the functions, we want to see them
2485 // early, so all call points have actual SPIR-V functions to reference.
2486 // In all cases, still let the traverser visit the children for us.
2487 makeFunctions(node->getAsAggregate()->getSequence());
2488
John Kessenich6fccb3c2016-09-19 16:01:41 -06002489 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002490 // anything else gets there, so visit out of order, doing them all now.
2491 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2492
John Kessenich6a60c2f2016-12-08 21:01:59 -07002493 // 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 -06002494 // so do them manually.
2495 visitFunctions(node->getAsAggregate()->getSequence());
2496
2497 return false;
2498 }
2499
2500 return true;
2501 }
2502 case glslang::EOpLinkerObjects:
2503 {
2504 if (visit == glslang::EvPreVisit)
2505 linkageOnly = true;
2506 else
2507 linkageOnly = false;
2508
2509 return true;
2510 }
2511 case glslang::EOpComma:
2512 {
2513 // processing from left to right naturally leaves the right-most
2514 // lying around in the access chain
2515 glslang::TIntermSequence& glslangOperands = node->getSequence();
2516 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2517 glslangOperands[i]->traverse(this);
2518
2519 return false;
2520 }
2521 case glslang::EOpFunction:
2522 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002523 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002524 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002525 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002526 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002527 } else {
2528 handleFunctionEntry(node);
2529 }
2530 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002531 if (inEntryPoint)
2532 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002533 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002534 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002535 }
2536
2537 return true;
2538 case glslang::EOpParameters:
2539 // Parameters will have been consumed by EOpFunction processing, but not
2540 // the body, so we still visited the function node's children, making this
2541 // child redundant.
2542 return false;
2543 case glslang::EOpFunctionCall:
2544 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002545 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002546 if (node->isUserDefined())
2547 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002548 if (result) {
2549 builder.clearAccessChain();
2550 builder.setAccessChainRValue(result);
2551 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002552 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002553
2554 return false;
2555 }
2556 case glslang::EOpConstructMat2x2:
2557 case glslang::EOpConstructMat2x3:
2558 case glslang::EOpConstructMat2x4:
2559 case glslang::EOpConstructMat3x2:
2560 case glslang::EOpConstructMat3x3:
2561 case glslang::EOpConstructMat3x4:
2562 case glslang::EOpConstructMat4x2:
2563 case glslang::EOpConstructMat4x3:
2564 case glslang::EOpConstructMat4x4:
2565 case glslang::EOpConstructDMat2x2:
2566 case glslang::EOpConstructDMat2x3:
2567 case glslang::EOpConstructDMat2x4:
2568 case glslang::EOpConstructDMat3x2:
2569 case glslang::EOpConstructDMat3x3:
2570 case glslang::EOpConstructDMat3x4:
2571 case glslang::EOpConstructDMat4x2:
2572 case glslang::EOpConstructDMat4x3:
2573 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002574 case glslang::EOpConstructIMat2x2:
2575 case glslang::EOpConstructIMat2x3:
2576 case glslang::EOpConstructIMat2x4:
2577 case glslang::EOpConstructIMat3x2:
2578 case glslang::EOpConstructIMat3x3:
2579 case glslang::EOpConstructIMat3x4:
2580 case glslang::EOpConstructIMat4x2:
2581 case glslang::EOpConstructIMat4x3:
2582 case glslang::EOpConstructIMat4x4:
2583 case glslang::EOpConstructUMat2x2:
2584 case glslang::EOpConstructUMat2x3:
2585 case glslang::EOpConstructUMat2x4:
2586 case glslang::EOpConstructUMat3x2:
2587 case glslang::EOpConstructUMat3x3:
2588 case glslang::EOpConstructUMat3x4:
2589 case glslang::EOpConstructUMat4x2:
2590 case glslang::EOpConstructUMat4x3:
2591 case glslang::EOpConstructUMat4x4:
2592 case glslang::EOpConstructBMat2x2:
2593 case glslang::EOpConstructBMat2x3:
2594 case glslang::EOpConstructBMat2x4:
2595 case glslang::EOpConstructBMat3x2:
2596 case glslang::EOpConstructBMat3x3:
2597 case glslang::EOpConstructBMat3x4:
2598 case glslang::EOpConstructBMat4x2:
2599 case glslang::EOpConstructBMat4x3:
2600 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002601 case glslang::EOpConstructF16Mat2x2:
2602 case glslang::EOpConstructF16Mat2x3:
2603 case glslang::EOpConstructF16Mat2x4:
2604 case glslang::EOpConstructF16Mat3x2:
2605 case glslang::EOpConstructF16Mat3x3:
2606 case glslang::EOpConstructF16Mat3x4:
2607 case glslang::EOpConstructF16Mat4x2:
2608 case glslang::EOpConstructF16Mat4x3:
2609 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002610 isMatrix = true;
2611 // fall through
2612 case glslang::EOpConstructFloat:
2613 case glslang::EOpConstructVec2:
2614 case glslang::EOpConstructVec3:
2615 case glslang::EOpConstructVec4:
2616 case glslang::EOpConstructDouble:
2617 case glslang::EOpConstructDVec2:
2618 case glslang::EOpConstructDVec3:
2619 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002620 case glslang::EOpConstructFloat16:
2621 case glslang::EOpConstructF16Vec2:
2622 case glslang::EOpConstructF16Vec3:
2623 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002624 case glslang::EOpConstructBool:
2625 case glslang::EOpConstructBVec2:
2626 case glslang::EOpConstructBVec3:
2627 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002628 case glslang::EOpConstructInt8:
2629 case glslang::EOpConstructI8Vec2:
2630 case glslang::EOpConstructI8Vec3:
2631 case glslang::EOpConstructI8Vec4:
2632 case glslang::EOpConstructUint8:
2633 case glslang::EOpConstructU8Vec2:
2634 case glslang::EOpConstructU8Vec3:
2635 case glslang::EOpConstructU8Vec4:
2636 case glslang::EOpConstructInt16:
2637 case glslang::EOpConstructI16Vec2:
2638 case glslang::EOpConstructI16Vec3:
2639 case glslang::EOpConstructI16Vec4:
2640 case glslang::EOpConstructUint16:
2641 case glslang::EOpConstructU16Vec2:
2642 case glslang::EOpConstructU16Vec3:
2643 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002644 case glslang::EOpConstructInt:
2645 case glslang::EOpConstructIVec2:
2646 case glslang::EOpConstructIVec3:
2647 case glslang::EOpConstructIVec4:
2648 case glslang::EOpConstructUint:
2649 case glslang::EOpConstructUVec2:
2650 case glslang::EOpConstructUVec3:
2651 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002652 case glslang::EOpConstructInt64:
2653 case glslang::EOpConstructI64Vec2:
2654 case glslang::EOpConstructI64Vec3:
2655 case glslang::EOpConstructI64Vec4:
2656 case glslang::EOpConstructUint64:
2657 case glslang::EOpConstructU64Vec2:
2658 case glslang::EOpConstructU64Vec3:
2659 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002660 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002661 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002662 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002663 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002664 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002665 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002666 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002667 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002668 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002669 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002670 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002671 else if (node->getOp() == glslang::EOpConstructStruct ||
2672 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2673 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002674 std::vector<spv::Id> constituents;
2675 for (int c = 0; c < (int)arguments.size(); ++c)
2676 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002677 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002678 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002679 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002680 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002681 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002682
Bas Nieuwenhuizenc9ffeec2020-09-03 03:09:39 +02002683 if (node->getType().getQualifier().isNonUniform()) {
2684 builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
2685 }
2686
John Kessenich140f3df2015-06-26 16:58:36 -06002687 builder.clearAccessChain();
2688 builder.setAccessChainRValue(constructed);
2689
2690 return false;
2691 }
2692
2693 // These six are component-wise compares with component-wise results.
2694 // Forward on to createBinaryOperation(), requesting a vector result.
2695 case glslang::EOpLessThan:
2696 case glslang::EOpGreaterThan:
2697 case glslang::EOpLessThanEqual:
2698 case glslang::EOpGreaterThanEqual:
2699 case glslang::EOpVectorEqual:
2700 case glslang::EOpVectorNotEqual:
2701 {
2702 // Map the operation to a binary
2703 binOp = node->getOp();
2704 reduceComparison = false;
2705 switch (node->getOp()) {
2706 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2707 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2708 default: binOp = node->getOp(); break;
2709 }
2710
2711 break;
2712 }
2713 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002714 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002715 binOp = glslang::EOpMul;
2716 break;
2717 case glslang::EOpOuterProduct:
2718 // two vectors multiplied to make a matrix
2719 binOp = glslang::EOpOuterProduct;
2720 break;
2721 case glslang::EOpDot:
2722 {
qining25262b32016-05-06 17:25:16 -04002723 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002724 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002725 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002726 binOp = glslang::EOpMul;
2727 break;
2728 }
2729 case glslang::EOpMod:
2730 // when an aggregate, this is the floating-point mod built-in function,
2731 // which can be emitted by the one in createBinaryOperation()
2732 binOp = glslang::EOpMod;
2733 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002734
John Kessenich140f3df2015-06-26 16:58:36 -06002735 case glslang::EOpEmitVertex:
2736 case glslang::EOpEndPrimitive:
2737 case glslang::EOpBarrier:
2738 case glslang::EOpMemoryBarrier:
2739 case glslang::EOpMemoryBarrierAtomicCounter:
2740 case glslang::EOpMemoryBarrierBuffer:
2741 case glslang::EOpMemoryBarrierImage:
2742 case glslang::EOpMemoryBarrierShared:
2743 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002744 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002745 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002746 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002747 case glslang::EOpWorkgroupMemoryBarrier:
2748 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002749 case glslang::EOpSubgroupBarrier:
2750 case glslang::EOpSubgroupMemoryBarrier:
2751 case glslang::EOpSubgroupMemoryBarrierBuffer:
2752 case glslang::EOpSubgroupMemoryBarrierImage:
2753 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002754 noReturnValue = true;
2755 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2756 break;
2757
John Kessenich426394d2015-07-23 10:22:48 -06002758 case glslang::EOpAtomicAdd:
2759 case glslang::EOpAtomicMin:
2760 case glslang::EOpAtomicMax:
2761 case glslang::EOpAtomicAnd:
2762 case glslang::EOpAtomicOr:
2763 case glslang::EOpAtomicXor:
2764 case glslang::EOpAtomicExchange:
2765 case glslang::EOpAtomicCompSwap:
2766 atomic = true;
2767 break;
2768
John Kesseniche5eee8f2019-10-18 01:03:11 -06002769#ifndef GLSLANG_WEB
2770 case glslang::EOpAtomicStore:
2771 noReturnValue = true;
2772 // fallthrough
2773 case glslang::EOpAtomicLoad:
2774 atomic = true;
2775 break;
2776
John Kessenich0d0c6d32017-07-23 16:08:26 -06002777 case glslang::EOpAtomicCounterAdd:
2778 case glslang::EOpAtomicCounterSubtract:
2779 case glslang::EOpAtomicCounterMin:
2780 case glslang::EOpAtomicCounterMax:
2781 case glslang::EOpAtomicCounterAnd:
2782 case glslang::EOpAtomicCounterOr:
2783 case glslang::EOpAtomicCounterXor:
2784 case glslang::EOpAtomicCounterExchange:
2785 case glslang::EOpAtomicCounterCompSwap:
2786 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2787 builder.addCapability(spv::CapabilityAtomicStorageOps);
2788 atomic = true;
2789 break;
2790
Ian Romanickb3bd4022019-01-21 08:57:25 -08002791 case glslang::EOpAbsDifference:
2792 case glslang::EOpAddSaturate:
2793 case glslang::EOpSubSaturate:
2794 case glslang::EOpAverage:
2795 case glslang::EOpAverageRounded:
2796 case glslang::EOpMul32x16:
2797 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2798 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2799 binOp = node->getOp();
2800 break;
2801
Daniel Kochdb32b242020-03-17 20:42:47 -04002802 case glslang::EOpIgnoreIntersection:
2803 case glslang::EOpTerminateRay:
2804 case glslang::EOpTrace:
2805 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002806 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2807 noReturnValue = true;
2808 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002809 case glslang::EOpRayQueryInitialize:
2810 case glslang::EOpRayQueryTerminate:
2811 case glslang::EOpRayQueryGenerateIntersection:
2812 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002813 builder.addExtension("SPV_KHR_ray_query");
2814 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002815 noReturnValue = true;
2816 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002817 case glslang::EOpRayQueryProceed:
2818 case glslang::EOpRayQueryGetIntersectionType:
2819 case glslang::EOpRayQueryGetRayTMin:
2820 case glslang::EOpRayQueryGetRayFlags:
2821 case glslang::EOpRayQueryGetIntersectionT:
2822 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2823 case glslang::EOpRayQueryGetIntersectionInstanceId:
2824 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2825 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2826 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2827 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2828 case glslang::EOpRayQueryGetIntersectionFrontFace:
2829 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2830 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2831 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2832 case glslang::EOpRayQueryGetWorldRayDirection:
2833 case glslang::EOpRayQueryGetWorldRayOrigin:
2834 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2835 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2836 builder.addExtension("SPV_KHR_ray_query");
2837 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2838 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002839 case glslang::EOpCooperativeMatrixLoad:
2840 case glslang::EOpCooperativeMatrixStore:
2841 noReturnValue = true;
2842 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002843 case glslang::EOpBeginInvocationInterlock:
2844 case glslang::EOpEndInvocationInterlock:
2845 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2846 noReturnValue = true;
2847 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002848#endif
Chao Chen3c366992018-09-19 11:41:59 -07002849
Jeff Bolz04d73732019-05-31 13:06:01 -05002850 case glslang::EOpDebugPrintf:
2851 noReturnValue = true;
2852 break;
2853
John Kessenich140f3df2015-06-26 16:58:36 -06002854 default:
2855 break;
2856 }
2857
2858 //
2859 // See if it maps to a regular operation.
2860 //
John Kessenich140f3df2015-06-26 16:58:36 -06002861 if (binOp != glslang::EOpNull) {
2862 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2863 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2864 assert(left && right);
2865
2866 builder.clearAccessChain();
2867 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002868 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002869
2870 builder.clearAccessChain();
2871 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002872 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002873
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002874 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002875 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002876 TranslateNoContractionDecoration(node->getType().getQualifier()),
2877 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002878 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002879 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002880 left->getType().getBasicType(), reduceComparison);
2881
2882 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002883 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002884 builder.clearAccessChain();
2885 builder.setAccessChainRValue(result);
2886
2887 return false;
2888 }
2889
John Kessenich426394d2015-07-23 10:22:48 -06002890 //
2891 // Create the list of operands.
2892 //
John Kessenich140f3df2015-06-26 16:58:36 -06002893 glslang::TIntermSequence& glslangOperands = node->getSequence();
2894 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002895 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002896 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002897 // special case l-value operands; there are just a few
2898 bool lvalue = false;
2899 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002900 case glslang::EOpModf:
2901 if (arg == 1)
2902 lvalue = true;
2903 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002904
Torosdagli06c2eee2020-03-19 11:09:57 -04002905 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002906 case glslang::EOpRayQueryTerminate:
2907 case glslang::EOpRayQueryConfirmIntersection:
2908 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002909 case glslang::EOpRayQueryGenerateIntersection:
2910 case glslang::EOpRayQueryGetIntersectionType:
2911 case glslang::EOpRayQueryGetIntersectionT:
2912 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2913 case glslang::EOpRayQueryGetIntersectionInstanceId:
2914 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2915 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2916 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2917 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2918 case glslang::EOpRayQueryGetIntersectionFrontFace:
2919 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2920 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2921 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2922 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2923 if (arg == 0)
2924 lvalue = true;
2925 break;
2926
John Kesseniche5eee8f2019-10-18 01:03:11 -06002927 case glslang::EOpAtomicAdd:
2928 case glslang::EOpAtomicMin:
2929 case glslang::EOpAtomicMax:
2930 case glslang::EOpAtomicAnd:
2931 case glslang::EOpAtomicOr:
2932 case glslang::EOpAtomicXor:
2933 case glslang::EOpAtomicExchange:
2934 case glslang::EOpAtomicCompSwap:
2935 if (arg == 0)
2936 lvalue = true;
2937 break;
2938
John Kessenicha28f7a72019-08-06 07:00:58 -06002939#ifndef GLSLANG_WEB
2940 case glslang::EOpFrexp:
2941 if (arg == 1)
2942 lvalue = true;
2943 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002944 case glslang::EOpInterpolateAtSample:
2945 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002946 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002947 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002948 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002949
2950 // Does it need a swizzle inversion? If so, evaluation is inverted;
2951 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002952 // That is, we transform
2953 //
2954 // interpolate(v.zy) -> interpolate(v).zy
2955 //
John Kessenichecba76f2017-01-06 00:34:48 -07002956 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002957 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002958 invertedType = convertGlslangToSpvType(
2959 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002960 }
Rex Xu7a26c172015-12-08 17:12:09 +08002961 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002962 case glslang::EOpAtomicLoad:
2963 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002964 case glslang::EOpAtomicCounterAdd:
2965 case glslang::EOpAtomicCounterSubtract:
2966 case glslang::EOpAtomicCounterMin:
2967 case glslang::EOpAtomicCounterMax:
2968 case glslang::EOpAtomicCounterAnd:
2969 case glslang::EOpAtomicCounterOr:
2970 case glslang::EOpAtomicCounterXor:
2971 case glslang::EOpAtomicCounterExchange:
2972 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002973 if (arg == 0)
2974 lvalue = true;
2975 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002976 case glslang::EOpAddCarry:
2977 case glslang::EOpSubBorrow:
2978 if (arg == 2)
2979 lvalue = true;
2980 break;
2981 case glslang::EOpUMulExtended:
2982 case glslang::EOpIMulExtended:
2983 if (arg >= 2)
2984 lvalue = true;
2985 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002986 case glslang::EOpCooperativeMatrixLoad:
2987 if (arg == 0 || arg == 1)
2988 lvalue = true;
2989 break;
2990 case glslang::EOpCooperativeMatrixStore:
2991 if (arg == 1)
2992 lvalue = true;
2993 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002994#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002995 default:
2996 break;
2997 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002998 builder.clearAccessChain();
2999 if (invertedType != spv::NoType && arg == 0)
3000 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
3001 else
3002 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003003
John Kessenichb9197c82019-08-11 07:41:45 -06003004#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003005 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
3006 node->getOp() == glslang::EOpCooperativeMatrixStore) {
3007
3008 if (arg == 1) {
3009 // fold "element" parameter into the access chain
3010 spv::Builder::AccessChain save = builder.getAccessChain();
3011 builder.clearAccessChain();
3012 glslangOperands[2]->traverse(this);
3013
3014 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
3015
3016 builder.setAccessChain(save);
3017
3018 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07003019 builder.accessChainPush(elementId,
3020 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
3021 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003022
3023 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3024 unsigned int alignment = builder.getAccessChain().alignment;
3025
3026 int memoryAccess = TranslateMemoryAccess(coherentFlags);
3027 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
3028 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
3029 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
3030 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07003031 if (builder.getStorageClass(builder.getAccessChain().base) ==
3032 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003033 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
3034 }
3035
3036 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
3037
3038 if (memoryAccess & spv::MemoryAccessAlignedMask) {
3039 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
3040 }
3041
John Kessenich8985fc92020-03-03 10:25:07 -07003042 if (memoryAccess &
3043 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
3044 memoryAccessOperands.push_back(spv::IdImmediate(true,
3045 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003046 }
3047 } else if (arg == 2) {
3048 continue;
3049 }
3050 }
John Kessenichb9197c82019-08-11 07:41:45 -06003051#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003052
John Kessenichbbbd9a22020-03-03 07:21:37 -07003053 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003054 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07003055 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
3056 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
3057 // reduce to a simple access chain. So, we need a temporary vector to
3058 // receive the result, and must later swizzle that into the original
3059 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06003060 complexLvalues.push_back(builder.getAccessChain());
John Kessenich435dd802020-06-30 01:27:08 -06003061 temporaryLvalues.push_back(builder.createVariable(
3062 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003063 builder.accessChainGetInferredType(), "swizzleTemp"));
3064 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003065 } else {
3066 operands.push_back(builder.accessChainGetLValue());
3067 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003068 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3069 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3070 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003071 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003072 glslang::TOperator glslangOp = node->getOp();
3073 if (arg == 1 &&
3074 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3075 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3076 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3077 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3078 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3079 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3080 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3081 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3082 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3083 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3084 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3085 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3086 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3087 )) {
3088 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3089 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3090 }
3091 else {
3092 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3093 }
3094
John Kesseniche485c7a2017-05-31 18:50:53 -06003095 }
John Kessenich140f3df2015-06-26 16:58:36 -06003096 }
John Kessenich426394d2015-07-23 10:22:48 -06003097
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003098 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003099#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003100 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3101 std::vector<spv::IdImmediate> idImmOps;
3102
3103 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3104 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3105 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3106 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3107 // get the pointee type
3108 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3109 assert(builder.isCooperativeMatrixType(typeId));
3110 // do the op
3111 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3112 // store the result to the pointer (out param 'm')
3113 builder.createStore(result, operands[0]);
3114 result = 0;
3115 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3116 std::vector<spv::IdImmediate> idImmOps;
3117
3118 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3119 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3120 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3121 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3122 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3123
3124 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3125 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003126 } else
3127#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003128 if (atomic) {
3129 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003130 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3131 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003132 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3133 if (!nonSemanticDebugPrintf) {
3134 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3135 }
3136 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3137 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003138 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003139 // Pass through to generic operations.
3140 switch (glslangOperands.size()) {
3141 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003142 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003143 break;
3144 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003145 {
3146 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003147 TranslateNoContractionDecoration(node->getType().getQualifier()),
3148 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003149 result = createUnaryOperation(
3150 node->getOp(), decorations,
3151 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003152 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003153 }
John Kessenich426394d2015-07-23 10:22:48 -06003154 break;
3155 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003156 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003157 break;
3158 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003159
John Kessenichbbbd9a22020-03-03 07:21:37 -07003160 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003161 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003162
3163 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3164 builder.setAccessChain(complexLvalues[i]);
greg-lunarg639f5462020-11-12 11:10:07 -07003165 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision),
3166 TranslateNonUniformDecoration(complexLvalues[i].coherentFlags));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003167 }
John Kessenich140f3df2015-06-26 16:58:36 -06003168 }
3169
3170 if (noReturnValue)
3171 return false;
3172
3173 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003174 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003175 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003176 } else {
3177 builder.clearAccessChain();
3178 builder.setAccessChainRValue(result);
3179 return false;
3180 }
3181}
3182
John Kessenich433e9ff2017-01-26 20:31:11 -07003183// This path handles both if-then-else and ?:
3184// The if-then-else has a node type of void, while
3185// ?: has either a void or a non-void node type
3186//
3187// Leaving the result, when not void:
3188// GLSL only has r-values as the result of a :?, but
3189// if we have an l-value, that can be more efficient if it will
3190// become the base of a complex r-value expression, because the
3191// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003192bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3193{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003194 // see if OpSelect can handle it
3195 const auto isOpSelectable = [&]() {
3196 if (node->getBasicType() == glslang::EbtVoid)
3197 return false;
3198 // OpSelect can do all other types starting with SPV 1.4
3199 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3200 // pre-1.4, only scalars and vectors can be handled
3201 if ((!node->getType().isScalar() && !node->getType().isVector()))
3202 return false;
3203 }
3204 return true;
3205 };
3206
John Kessenich4bee5312018-02-20 21:29:05 -07003207 // See if it simple and safe, or required, to execute both sides.
3208 // Crucially, side effects must be either semantically required or avoided,
3209 // and there are performance trade-offs.
3210 // Return true if required or a good idea (and safe) to execute both sides,
3211 // false otherwise.
3212 const auto bothSidesPolicy = [&]() -> bool {
3213 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003214 if (node->getTrueBlock() == nullptr ||
3215 node->getFalseBlock() == nullptr)
3216 return false;
3217
John Kessenich4bee5312018-02-20 21:29:05 -07003218 // required? (unless we write additional code to look for side effects
3219 // and make performance trade-offs if none are present)
3220 if (!node->getShortCircuit())
3221 return true;
3222
3223 // if not required to execute both, decide based on performance/practicality...
3224
John Kessenich0c1e71a2019-01-10 18:23:06 +07003225 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003226 return false;
3227
John Kessenich433e9ff2017-01-26 20:31:11 -07003228 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3229 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3230
3231 // return true if a single operand to ? : is okay for OpSelect
3232 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003233 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003234 };
3235
3236 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3237 operandOkay(node->getFalseBlock()->getAsTyped());
3238 };
3239
John Kessenich4bee5312018-02-20 21:29:05 -07003240 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3241 // emit the condition before doing anything with selection
3242 node->getCondition()->traverse(this);
3243 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3244
3245 // Find a way of executing both sides and selecting the right result.
3246 const auto executeBothSides = [&]() -> void {
3247 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003248 node->getTrueBlock()->traverse(this);
3249 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3250 node->getFalseBlock()->traverse(this);
3251 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3252
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003253 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003254
John Kessenich4bee5312018-02-20 21:29:05 -07003255 // done if void
3256 if (node->getBasicType() == glslang::EbtVoid)
3257 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003258
John Kessenich4bee5312018-02-20 21:29:05 -07003259 // emit code to select between trueValue and falseValue
3260
3261 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003262 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003263 // Emit OpSelect for this selection.
3264
3265 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003266 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3267 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003268 condition = builder.smearScalar(spv::NoPrecision, condition,
3269 builder.makeVectorType(builder.makeBoolType(),
3270 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003271 }
John Kessenich4bee5312018-02-20 21:29:05 -07003272
3273 // OpSelect
3274 result = builder.createTriOp(spv::OpSelect,
3275 convertGlslangToSpvType(node->getType()), condition,
3276 trueValue, falseValue);
3277
3278 builder.clearAccessChain();
3279 builder.setAccessChainRValue(result);
3280 } else {
3281 // We need control flow to select the result.
3282 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003283 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3284 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003285
3286 // Selection control:
3287 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3288
3289 // make an "if" based on the value created by the condition
3290 spv::Builder::If ifBuilder(condition, control, builder);
3291
3292 // emit the "then" statement
3293 builder.createStore(trueValue, result);
3294 ifBuilder.makeBeginElse();
3295 // emit the "else" statement
3296 builder.createStore(falseValue, result);
3297
3298 // finish off the control flow
3299 ifBuilder.makeEndIf();
3300
3301 builder.clearAccessChain();
3302 builder.setAccessChainLValue(result);
3303 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003304 };
3305
John Kessenich4bee5312018-02-20 21:29:05 -07003306 // Execute the one side needed, as per the condition
3307 const auto executeOneSide = [&]() {
3308 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003309 if (node->getBasicType() != glslang::EbtVoid) {
3310 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3311 convertGlslangToSpvType(node->getType()));
3312 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003313
John Kessenich4bee5312018-02-20 21:29:05 -07003314 // Selection control:
3315 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3316
3317 // make an "if" based on the value created by the condition
3318 spv::Builder::If ifBuilder(condition, control, builder);
3319
3320 // emit the "then" statement
3321 if (node->getTrueBlock() != nullptr) {
3322 node->getTrueBlock()->traverse(this);
3323 if (result != spv::NoResult)
3324 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3325 }
3326
3327 if (node->getFalseBlock() != nullptr) {
3328 ifBuilder.makeBeginElse();
3329 // emit the "else" statement
3330 node->getFalseBlock()->traverse(this);
3331 if (result != spv::NoResult)
3332 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3333 }
3334
3335 // finish off the control flow
3336 ifBuilder.makeEndIf();
3337
3338 if (result != spv::NoResult) {
3339 builder.clearAccessChain();
3340 builder.setAccessChainLValue(result);
3341 }
3342 };
3343
3344 // Try for OpSelect (or a requirement to execute both sides)
3345 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003346 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3347 if (node->getType().getQualifier().isSpecConstant())
3348 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003349 executeBothSides();
3350 } else
3351 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003352
3353 return false;
3354}
3355
3356bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3357{
3358 // emit and get the condition before doing anything with switch
3359 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003360 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003361
Rex Xu57e65922017-07-04 23:23:40 +08003362 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003363 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003364
John Kessenich140f3df2015-06-26 16:58:36 -06003365 // browse the children to sort out code segments
3366 int defaultSegment = -1;
3367 std::vector<TIntermNode*> codeSegments;
3368 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3369 std::vector<int> caseValues;
3370 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3371 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3372 TIntermNode* child = *c;
3373 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003374 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003375 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003376 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003377 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3378 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003379 } else
3380 codeSegments.push_back(child);
3381 }
3382
qining25262b32016-05-06 17:25:16 -04003383 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003384 // statements between the last case and the end of the switch statement
3385 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3386 (int)codeSegments.size() == defaultSegment)
3387 codeSegments.push_back(nullptr);
3388
3389 // make the switch statement
3390 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003391 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3392 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003393
3394 // emit all the code in the segments
3395 breakForLoop.push(false);
3396 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3397 builder.nextSwitchSegment(segmentBlocks, s);
3398 if (codeSegments[s])
3399 codeSegments[s]->traverse(this);
3400 else
3401 builder.addSwitchBreak();
3402 }
3403 breakForLoop.pop();
3404
3405 builder.endSwitch(segmentBlocks);
3406
3407 return false;
3408}
3409
3410void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3411{
3412 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003413 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003414
3415 builder.clearAccessChain();
3416 builder.setAccessChainRValue(constant);
3417}
3418
3419bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3420{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003421 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003422 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003423
3424 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003425 std::vector<unsigned int> operands;
3426 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003427
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003428 // Spec requires back edges to target header blocks, and every header block
3429 // must dominate its merge block. Make a header block first to ensure these
3430 // conditions are met. By definition, it will contain OpLoopMerge, followed
3431 // by a block-ending branch. But we don't want to put any other body/test
3432 // instructions in it, since the body/test may have arbitrary instructions,
3433 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003434 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003435 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003436 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003437 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003438 spv::Block& test = builder.makeNewBlock();
3439 builder.createBranch(&test);
3440
3441 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003442 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003443 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003444 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3445
3446 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003447 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003448 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003449 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003450 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003451 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003452
3453 builder.setBuildPoint(&blocks.continue_target);
3454 if (node->getTerminal())
3455 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003456 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003457 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003458 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003459 builder.createBranch(&blocks.body);
3460
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003461 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003462 builder.setBuildPoint(&blocks.body);
3463 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003464 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003465 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003466 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003467
3468 builder.setBuildPoint(&blocks.continue_target);
3469 if (node->getTerminal())
3470 node->getTerminal()->traverse(this);
3471 if (node->getTest()) {
3472 node->getTest()->traverse(this);
3473 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003474 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003475 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003476 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003477 // TODO: unless there was a break/return/discard instruction
3478 // somewhere in the body, this is an infinite loop, so we should
3479 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003480 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003481 }
John Kessenich140f3df2015-06-26 16:58:36 -06003482 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003483 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003484 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003485 return false;
3486}
3487
3488bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3489{
3490 if (node->getExpression())
3491 node->getExpression()->traverse(this);
3492
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003493 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003494
John Kessenich140f3df2015-06-26 16:58:36 -06003495 switch (node->getFlowOp()) {
3496 case glslang::EOpKill:
3497 builder.makeDiscard();
3498 break;
Jesse Hall74e8f052020-11-09 08:30:01 -08003499 case glslang::EOpTerminateInvocation:
3500 builder.addExtension(spv::E_SPV_KHR_terminate_invocation);
3501 builder.makeTerminateInvocation();
3502 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003503 case glslang::EOpBreak:
3504 if (breakForLoop.top())
3505 builder.createLoopExit();
3506 else
3507 builder.addSwitchBreak();
3508 break;
3509 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003510 builder.createLoopContinue();
3511 break;
3512 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003513 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003514 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3515 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003516 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3517 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003518 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003519 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3520 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003521 builder.setAccessChainLValue(copyId);
3522 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003523 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003524 }
3525 builder.makeReturn(false, returnId);
3526 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003527 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003528
3529 builder.clearAccessChain();
3530 break;
3531
John Kessenichb9197c82019-08-11 07:41:45 -06003532#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003533 case glslang::EOpDemote:
3534 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3535 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3536 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3537 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003538#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003539
John Kessenich140f3df2015-06-26 16:58:36 -06003540 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003541 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003542 break;
3543 }
3544
3545 return false;
3546}
3547
John Kessenich9c14f772019-06-17 08:38:35 -06003548spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003549{
qining25262b32016-05-06 17:25:16 -04003550 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003551 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003552 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003553 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003554 spv::Id result = createSpvConstant(*node);
3555 if (result != spv::NoResult)
3556 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003557 }
3558
3559 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003560 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003561 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3562 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003563
John Kessenichb9197c82019-08-11 07:41:45 -06003564 const bool contains16BitType = node->getType().contains16BitFloat() ||
3565 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003566 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003567 switch (storageClass) {
3568 case spv::StorageClassInput:
3569 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003570 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003571 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003572 break;
John Kessenich18310872018-05-14 22:08:53 -06003573 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003574 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003575 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3576 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003577 else
3578 builder.addCapability(spv::CapabilityStorageUniform16);
3579 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003580#ifndef GLSLANG_WEB
3581 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003582 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003583 builder.addCapability(spv::CapabilityStoragePushConstant16);
3584 break;
John Kessenich18310872018-05-14 22:08:53 -06003585 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003586 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003587 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003588 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3589 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003590#endif
John Kessenich18310872018-05-14 22:08:53 -06003591 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003592 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003593 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003594 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003595 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003596 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003597 }
3598 }
Rex Xuf89ad982017-04-07 23:22:33 +08003599
John Kessenichb9197c82019-08-11 07:41:45 -06003600 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003601 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003602 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003603 builder.addCapability(spv::CapabilityStoragePushConstant8);
3604 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003605 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003606 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003607 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003608 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003609 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003610 } else {
3611 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003612 }
3613 }
3614
John Kessenich140f3df2015-06-26 16:58:36 -06003615 const char* name = node->getName().c_str();
3616 if (glslang::IsAnonymous(name))
3617 name = "";
3618
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003619 spv::Id initializer = spv::NoResult;
3620
3621 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3622 !node->getConstArray().empty()) {
3623 int nextConst = 0;
3624 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3625 node->getConstArray(),
3626 nextConst,
3627 false /* specConst */);
3628 }
3629
John Kessenich435dd802020-06-30 01:27:08 -06003630 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003631}
3632
3633// Return type Id of the sampled type.
3634spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3635{
3636 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003637 case glslang::EbtInt: return builder.makeIntType(32);
3638 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003639 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003640#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003641 case glslang::EbtFloat16:
3642 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3643 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3644 return builder.makeFloatType(16);
Tobski8c1a3a02020-11-04 16:24:23 +00003645 case glslang::EbtInt64: return builder.makeIntType(64);
3646 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3647 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3648 case glslang::EbtUint64: return builder.makeUintType(64);
3649 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3650 builder.addCapability(spv::CapabilityFloat16ImageAMD);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003651#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003652 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003653 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003654 return builder.makeFloatType(32);
3655 }
3656}
3657
John Kessenich8c8505c2016-07-26 12:50:38 -06003658// If node is a swizzle operation, return the type that should be used if
3659// the swizzle base is first consumed by another operation, before the swizzle
3660// is applied.
3661spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3662{
John Kessenichecba76f2017-01-06 00:34:48 -07003663 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003664 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3665 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3666 else
3667 return spv::NoType;
3668}
3669
3670// When inverting a swizzle with a parent op, this function
3671// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003672spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3673 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003674{
3675 std::vector<unsigned> swizzle;
3676 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3677 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3678}
3679
John Kessenich8c8505c2016-07-26 12:50:38 -06003680// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3681void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3682{
3683 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3684 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3685 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3686}
3687
John Kessenich3ac051e2015-12-20 11:29:16 -07003688// Convert from a glslang type to an SPV type, by calling into a
3689// recursive version of this function. This establishes the inherited
3690// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003691spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003692{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003693 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003694}
3695
3696// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003697// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003698// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003699spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003700 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3701 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003702{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003703 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003704
3705 switch (type.getBasicType()) {
3706 case glslang::EbtVoid:
3707 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003708 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003710 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003711 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3712 // a 32-bit int where non-0 means true.
3713 if (explicitLayout != glslang::ElpNone)
3714 spvType = builder.makeUintType(32);
3715 else
3716 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003717 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003718 case glslang::EbtInt:
3719 spvType = builder.makeIntType(32);
3720 break;
3721 case glslang::EbtUint:
3722 spvType = builder.makeUintType(32);
3723 break;
3724 case glslang::EbtFloat:
3725 spvType = builder.makeFloatType(32);
3726 break;
3727#ifndef GLSLANG_WEB
3728 case glslang::EbtDouble:
3729 spvType = builder.makeFloatType(64);
3730 break;
3731 case glslang::EbtFloat16:
3732 spvType = builder.makeFloatType(16);
3733 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003734 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003735 spvType = builder.makeIntType(8);
3736 break;
3737 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003738 spvType = builder.makeUintType(8);
3739 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003740 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003741 spvType = builder.makeIntType(16);
3742 break;
3743 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003744 spvType = builder.makeUintType(16);
3745 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003746 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003747 spvType = builder.makeIntType(64);
3748 break;
3749 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003750 spvType = builder.makeUintType(64);
3751 break;
John Kessenich426394d2015-07-23 10:22:48 -06003752 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003753 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003754 spvType = builder.makeUintType(32);
3755 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003756 case glslang::EbtAccStruct:
3757 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003758 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003759 case glslang::EbtRayQuery:
3760 spvType = builder.makeRayQueryType();
3761 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003762 case glslang::EbtReference:
3763 {
3764 // Make the forward pointer, then recurse to convert the structure type, then
3765 // patch up the forward pointer with a real pointer type.
3766 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3767 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3768 forwardPointers[type.getReferentType()] = forwardId;
3769 }
3770 spvType = forwardPointers[type.getReferentType()];
3771 if (!forwardReferenceOnly) {
3772 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3773 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3774 forwardPointers[type.getReferentType()],
3775 referentType);
3776 }
3777 }
3778 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003779#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003780 case glslang::EbtSampler:
3781 {
3782 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003783 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003784 spvType = builder.makeSamplerType();
3785 } else {
3786 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003787 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3788 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3789 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3790 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003791 // already has both image and sampler, make the combined type
3792 spvType = builder.makeSampledImageType(spvType);
3793 }
John Kessenich55e7d112015-11-15 21:33:39 -07003794 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003795 }
John Kessenich140f3df2015-06-26 16:58:36 -06003796 break;
3797 case glslang::EbtStruct:
3798 case glslang::EbtBlock:
3799 {
3800 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003801 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003802
3803 // Try to share structs for different layouts, but not yet for other
3804 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003805 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003806 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003807 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003808 break;
3809
3810 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003811 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003812 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003813 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003814 }
3815 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003816 case glslang::EbtString:
3817 // no type used for OpString
3818 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003819 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003820 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003821 break;
3822 }
3823
3824 if (type.isMatrix())
3825 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3826 else {
3827 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3828 if (type.getVectorSize() > 1)
3829 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3830 }
3831
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003832 if (type.isCoopMat()) {
3833 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3834 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3835 if (type.getBasicType() == glslang::EbtFloat16)
3836 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003837 if (type.getBasicType() == glslang::EbtUint8 ||
3838 type.getBasicType() == glslang::EbtInt8) {
3839 builder.addCapability(spv::CapabilityInt8);
3840 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003841
3842 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3843 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3844 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3845
3846 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3847 }
3848
John Kessenich140f3df2015-06-26 16:58:36 -06003849 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003850 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3851
John Kessenichc9a80832015-09-12 12:17:44 -06003852 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003853 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003854 // We need to decorate array strides for types needing explicit layout, except blocks.
3855 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003856 // Use a dummy glslang type for querying internal strides of
3857 // arrays of arrays, but using just a one-dimensional array.
3858 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003859 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3860 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003861
3862 // Will compute the higher-order strides here, rather than making a whole
3863 // pile of types and doing repetitive recursion on their contents.
3864 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3865 }
John Kessenichf8842e52016-01-04 19:22:56 -07003866
3867 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003868 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003869 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003870 if (stride > 0)
3871 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003872 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003873 }
3874 } else {
3875 // single-dimensional array, and don't yet have stride
3876
John Kessenichf8842e52016-01-04 19:22:56 -07003877 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003878 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3879 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003880 }
John Kessenich31ed4832015-09-09 17:51:38 -06003881
John Kessenichead86222018-03-28 18:01:20 -06003882 // Do the outer dimension, which might not be known for a runtime-sized array.
3883 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3884 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003885 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003886 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003887#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003888 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003889 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003890 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3891 }
John Kessenichb9197c82019-08-11 07:41:45 -06003892#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003893 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003894 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003895 if (stride > 0)
3896 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003897 }
3898
3899 return spvType;
3900}
3901
John Kessenich0e737842017-03-24 18:38:16 -06003902// TODO: this functionality should exist at a higher level, in creating the AST
3903//
3904// Identify interface members that don't have their required extension turned on.
3905//
3906bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3907{
John Kessenicha28f7a72019-08-06 07:00:58 -06003908#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003909 auto& extensions = glslangIntermediate->getRequestedExtensions();
3910
Rex Xubcf291a2017-03-29 23:01:36 +08003911 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3912 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3913 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003914 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3915 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3916 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003917
3918 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3919 if (member.getFieldName() == "gl_ViewportMask" &&
3920 extensions.find("GL_NV_viewport_array2") == extensions.end())
3921 return true;
3922 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3923 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3924 return true;
3925 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3926 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3927 return true;
3928 }
3929#endif
John Kessenich0e737842017-03-24 18:38:16 -06003930
3931 return false;
3932};
3933
John Kessenich6090df02016-06-30 21:18:02 -06003934// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3935// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3936// Mutually recursive with convertGlslangToSpvType().
3937spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3938 const glslang::TTypeList* glslangMembers,
3939 glslang::TLayoutPacking explicitLayout,
3940 const glslang::TQualifier& qualifier)
3941{
3942 // Create a vector of struct types for SPIR-V to consume
3943 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003944 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3945 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003946 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003947 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3948 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3949 if (glslangMember.hiddenMember()) {
3950 ++memberDelta;
3951 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003952 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003953 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003954 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003955 if (filterMember(glslangMember)) {
3956 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003957 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003958 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003959 }
Roy05a5b532020-01-03 16:21:34 +08003960 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003961 }
John Kessenich6090df02016-06-30 21:18:02 -06003962 // modify just this child's view of the qualifier
3963 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3964 InheritQualifiers(memberQualifier, qualifier);
3965
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003966 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003967 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003968 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003969
3970 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003971 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3972 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003973
3974 // Make forward pointers for any pointer members, and create a list of members to
3975 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003976 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003977 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3978 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3979 }
3980 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003981 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3982 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003983 } else {
3984 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003985 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3986 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003987 }
John Kessenich6090df02016-06-30 21:18:02 -06003988 }
3989 }
3990
3991 // Make the SPIR-V type
3992 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003993 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003994 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3995
3996 // Decorate it
3997 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3998
John Kessenichd72f4882019-01-16 14:55:37 +07003999 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004000 auto it = deferredForwardPointers[i];
4001 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
4002 }
4003
John Kessenich6090df02016-06-30 21:18:02 -06004004 return spvType;
4005}
4006
4007void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
4008 const glslang::TTypeList* glslangMembers,
4009 glslang::TLayoutPacking explicitLayout,
4010 const glslang::TQualifier& qualifier,
4011 spv::Id spvType)
4012{
4013 // Name and decorate the non-hidden members
4014 int offset = -1;
4015 int locationOffset = 0; // for use within the members of this struct
Chow478b2322020-11-04 04:34:19 +08004016 bool memberLocationInvalid = type.isArrayOfArrays() ||
4017 (type.isArray() && (type.getQualifier().isArrayedIo(glslangIntermediate->getStage()) == false));
John Kessenich6090df02016-06-30 21:18:02 -06004018 for (int i = 0; i < (int)glslangMembers->size(); i++) {
4019 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
4020 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06004021 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08004022 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06004023 if (filterMember(glslangMember))
4024 continue;
4025 }
John Kessenich6090df02016-06-30 21:18:02 -06004026
4027 // modify just this child's view of the qualifier
4028 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
4029 InheritQualifiers(memberQualifier, qualifier);
4030
4031 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07004032 if (member < 0)
4033 continue;
4034
4035 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
4036 builder.addMemberDecoration(spvType, member,
4037 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
4038 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
4039 // Add interpolation and auxiliary storage decorations only to
4040 // top-level members of Input and Output storage classes
4041 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
4042 type.getQualifier().storage == glslang::EvqVaryingOut) {
4043 if (type.getBasicType() == glslang::EbtBlock ||
4044 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
4045 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
4046 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06004047#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07004048 addMeshNVDecoration(spvType, member, memberQualifier);
4049#endif
John Kessenich6090df02016-06-30 21:18:02 -06004050 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004051 }
4052 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06004053
John Kessenichb9197c82019-08-11 07:41:45 -06004054#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07004055 if (type.getBasicType() == glslang::EbtBlock &&
4056 qualifier.storage == glslang::EvqBuffer) {
4057 // Add memory decorations only to top-level members of shader storage block
4058 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05004059 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07004060 for (unsigned int i = 0; i < memory.size(); ++i)
4061 builder.addMemberDecoration(spvType, member, memory[i]);
4062 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004063
John Kessenichb9197c82019-08-11 07:41:45 -06004064#endif
John Kessenich6090df02016-06-30 21:18:02 -06004065
John Kessenich5d610ee2018-03-07 18:05:55 -07004066 // Location assignment was already completed correctly by the front end,
4067 // just track whether a member needs to be decorated.
4068 // Ignore member locations if the container is an array, as that's
4069 // ill-specified and decisions have been made to not allow this.
Chow478b2322020-11-04 04:34:19 +08004070 if (!memberLocationInvalid && memberQualifier.hasLocation())
John Kessenich5d610ee2018-03-07 18:05:55 -07004071 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004072
John Kessenich5d610ee2018-03-07 18:05:55 -07004073 if (qualifier.hasLocation()) // track for upcoming inheritance
4074 locationOffset += glslangIntermediate->computeTypeLocationSize(
4075 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004076
John Kessenich5d610ee2018-03-07 18:05:55 -07004077 // component, XFB, others
4078 if (glslangMember.getQualifier().hasComponent())
4079 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4080 glslangMember.getQualifier().layoutComponent);
4081 if (glslangMember.getQualifier().hasXfbOffset())
4082 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4083 glslangMember.getQualifier().layoutXfbOffset);
4084 else if (explicitLayout != glslang::ElpNone) {
4085 // figure out what to do with offset, which is accumulating
4086 int nextOffset;
4087 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4088 if (offset >= 0)
4089 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4090 offset = nextOffset;
4091 }
John Kessenich6090df02016-06-30 21:18:02 -06004092
John Kessenich5d610ee2018-03-07 18:05:55 -07004093 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4094 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4095 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004096
John Kessenich5d610ee2018-03-07 18:05:55 -07004097 // built-in variable decorations
4098 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4099 if (builtIn != spv::BuiltInMax)
4100 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004101
John Kessenichb9197c82019-08-11 07:41:45 -06004102#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004103 // nonuniform
4104 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4105
John Kessenichead86222018-03-28 18:01:20 -06004106 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4107 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4108 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4109 memberQualifier.semanticName);
4110 }
4111
John Kessenich5d610ee2018-03-07 18:05:55 -07004112 if (builtIn == spv::BuiltInLayer) {
4113 // SPV_NV_viewport_array2 extension
4114 if (glslangMember.getQualifier().layoutViewportRelative){
4115 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4116 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4117 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004118 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004119 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4120 builder.addMemberDecoration(spvType, member,
4121 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4122 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4123 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4124 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004125 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004126 }
4127 if (glslangMember.getQualifier().layoutPassthrough) {
4128 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4129 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4130 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4131 }
chaoc771d89f2017-01-13 01:10:53 -08004132#endif
John Kessenich6090df02016-06-30 21:18:02 -06004133 }
4134
4135 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004136 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4137 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004138}
4139
John Kessenich6c292d32016-02-15 20:58:50 -07004140// Turn the expression forming the array size into an id.
4141// This is not quite trivial, because of specialization constants.
4142// Sometimes, a raw constant is turned into an Id, and sometimes
4143// a specialization constant expression is.
4144spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4145{
4146 // First, see if this is sized with a node, meaning a specialization constant:
4147 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4148 if (specNode != nullptr) {
4149 builder.clearAccessChain();
4150 specNode->traverse(this);
4151 return accessChainLoad(specNode->getAsTyped()->getType());
4152 }
qining25262b32016-05-06 17:25:16 -04004153
John Kessenich6c292d32016-02-15 20:58:50 -07004154 // Otherwise, need a compile-time (front end) size, get it:
4155 int size = arraySizes.getDimSize(dim);
4156 assert(size > 0);
4157 return builder.makeUintConstant(size);
4158}
4159
John Kessenich103bef92016-02-08 21:38:15 -07004160// Wrap the builder's accessChainLoad to:
4161// - localize handling of RelaxedPrecision
4162// - use the SPIR-V inferred type instead of another conversion of the glslang type
4163// (avoids unnecessary work and possible type punning for structures)
4164// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004165spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4166{
John Kessenich103bef92016-02-08 21:38:15 -07004167 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004168
4169 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4170 coherentFlags |= TranslateCoherent(type);
4171
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004172 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004173 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004174
John Kessenich5611c6d2018-04-05 11:25:02 -06004175 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
greg-lunarg639f5462020-11-12 11:10:07 -07004176 TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004177 TranslateNonUniformDecoration(type.getQualifier()),
4178 nominalTypeId,
4179 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4180 TranslateMemoryScope(coherentFlags),
4181 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004182
4183 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004184 if (type.getBasicType() == glslang::EbtBool) {
4185 if (builder.isScalarType(nominalTypeId)) {
4186 // Conversion for bool
4187 spv::Id boolType = builder.makeBoolType();
4188 if (nominalTypeId != boolType)
4189 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4190 } else if (builder.isVectorType(nominalTypeId)) {
4191 // Conversion for bvec
4192 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4193 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4194 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004195 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4196 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004197 }
4198 }
John Kessenich103bef92016-02-08 21:38:15 -07004199
4200 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004201}
4202
Rex Xu27253232016-02-23 17:51:09 +08004203// Wrap the builder's accessChainStore to:
4204// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004205//
4206// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004207void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4208{
4209 // Need to convert to abstract types when necessary
4210 if (type.getBasicType() == glslang::EbtBool) {
4211 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4212
4213 if (builder.isScalarType(nominalTypeId)) {
4214 // Conversion for bool
4215 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004216 if (nominalTypeId != boolType) {
4217 // keep these outside arguments, for determinant order-of-evaluation
4218 spv::Id one = builder.makeUintConstant(1);
4219 spv::Id zero = builder.makeUintConstant(0);
4220 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4221 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004222 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004223 } else if (builder.isVectorType(nominalTypeId)) {
4224 // Conversion for bvec
4225 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4226 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004227 if (nominalTypeId != bvecType) {
4228 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004229 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4230 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4231 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004232 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004233 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4234 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004235 }
4236 }
4237
Jeff Bolz36831c92018-09-05 10:11:41 -05004238 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4239 coherentFlags |= TranslateCoherent(type);
4240
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004241 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004242 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004243
greg-lunarg639f5462020-11-12 11:10:07 -07004244 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
John Kessenich8985fc92020-03-03 10:25:07 -07004245 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4246 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004247 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004248}
4249
John Kessenich4bf71552016-09-02 11:20:21 -06004250// For storing when types match at the glslang level, but not might match at the
4251// SPIR-V level.
4252//
4253// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004254// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004255// as in a member-decorated way.
4256//
4257// NOTE: This function can handle any store request; if it's not special it
4258// simplifies to a simple OpStore.
4259//
4260// Implicitly uses the existing builder.accessChain as the storage target.
4261void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4262{
John Kessenichb3e24e42016-09-11 12:33:43 -06004263 // we only do the complex path here if it's an aggregate
4264 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004265 accessChainStore(type, rValue);
4266 return;
4267 }
4268
John Kessenichb3e24e42016-09-11 12:33:43 -06004269 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004270 spv::Id rType = builder.getTypeId(rValue);
4271 spv::Id lValue = builder.accessChainGetLValue();
4272 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4273 if (lType == rType) {
4274 accessChainStore(type, rValue);
4275 return;
4276 }
4277
John Kessenichb3e24e42016-09-11 12:33:43 -06004278 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004279 // where the two types were the same type in GLSL. This requires member
4280 // by member copy, recursively.
4281
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004282 // SPIR-V 1.4 added an instruction to do help do this.
4283 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4284 // However, bool in uniform space is changed to int, so
4285 // OpCopyLogical does not work for that.
4286 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4287 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4288 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4289 if (lBool == rBool) {
4290 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4291 accessChainStore(type, logicalCopy);
4292 return;
4293 }
4294 }
4295
John Kessenichb3e24e42016-09-11 12:33:43 -06004296 // If an array, copy element by element.
4297 if (type.isArray()) {
4298 glslang::TType glslangElementType(type, 0);
4299 spv::Id elementRType = builder.getContainedTypeId(rType);
4300 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4301 // get the source member
4302 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004303
John Kessenichb3e24e42016-09-11 12:33:43 -06004304 // set up the target storage
4305 builder.clearAccessChain();
4306 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004307 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4308 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004309
John Kessenichb3e24e42016-09-11 12:33:43 -06004310 // store the member
4311 multiTypeStore(glslangElementType, elementRValue);
4312 }
4313 } else {
4314 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004315
John Kessenichb3e24e42016-09-11 12:33:43 -06004316 // loop over structure members
4317 const glslang::TTypeList& members = *type.getStruct();
4318 for (int m = 0; m < (int)members.size(); ++m) {
4319 const glslang::TType& glslangMemberType = *members[m].type;
4320
4321 // get the source member
4322 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4323 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4324
4325 // set up the target storage
4326 builder.clearAccessChain();
4327 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004328 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4329 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004330
4331 // store the member
4332 multiTypeStore(glslangMemberType, memberRValue);
4333 }
John Kessenich4bf71552016-09-02 11:20:21 -06004334 }
4335}
4336
John Kessenichf85e8062015-12-19 13:57:10 -07004337// Decide whether or not this type should be
4338// decorated with offsets and strides, and if so
4339// whether std140 or std430 rules should be applied.
4340glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004341{
John Kessenichf85e8062015-12-19 13:57:10 -07004342 // has to be a block
4343 if (type.getBasicType() != glslang::EbtBlock)
4344 return glslang::ElpNone;
4345
Chao Chen3c366992018-09-19 11:41:59 -07004346 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004347 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004348 type.getQualifier().storage != glslang::EvqBuffer &&
4349 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004350 return glslang::ElpNone;
4351
4352 // return the layout to use
4353 switch (type.getQualifier().layoutPacking) {
4354 case glslang::ElpStd140:
4355 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004356 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004357 return type.getQualifier().layoutPacking;
4358 default:
4359 return glslang::ElpNone;
4360 }
John Kessenich31ed4832015-09-09 17:51:38 -06004361}
4362
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004363// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004364int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4365 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004366{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004367 int size;
John Kessenich49987892015-12-29 17:11:44 -07004368 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004369 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4370 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004371
4372 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004373}
4374
John Kessenich49987892015-12-29 17:11:44 -07004375// 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 -07004376// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004377int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4378 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004379{
John Kessenich49987892015-12-29 17:11:44 -07004380 glslang::TType elementType;
4381 elementType.shallowCopy(matrixType);
4382 elementType.clearArraySizes();
4383
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004384 int size;
John Kessenich49987892015-12-29 17:11:44 -07004385 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004386 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4387 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004388
4389 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004390}
4391
John Kessenich5e4b1242015-08-06 22:53:06 -06004392// Given a member type of a struct, realign the current offset for it, and compute
4393// the next (not yet aligned) offset for the next member, which will get aligned
4394// on the next call.
4395// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4396// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4397// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004398void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4399 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004400{
4401 // this will get a positive value when deemed necessary
4402 nextOffset = -1;
4403
John Kessenich5e4b1242015-08-06 22:53:06 -06004404 // override anything in currentOffset with user-set offset
4405 if (memberType.getQualifier().hasOffset())
4406 currentOffset = memberType.getQualifier().layoutOffset;
4407
4408 // It could be that current linker usage in glslang updated all the layoutOffset,
4409 // in which case the following code does not matter. But, that's not quite right
4410 // once cross-compilation unit GLSL validation is done, as the original user
4411 // settings are needed in layoutOffset, and then the following will come into play.
4412
John Kessenichf85e8062015-12-19 13:57:10 -07004413 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004414 if (! memberType.getQualifier().hasOffset())
4415 currentOffset = -1;
4416
4417 return;
4418 }
4419
John Kessenichf85e8062015-12-19 13:57:10 -07004420 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004421 if (currentOffset < 0)
4422 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004423
John Kessenich5e4b1242015-08-06 22:53:06 -06004424 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4425 // but possibly not yet correctly aligned.
4426
4427 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004428 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004429 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4430 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004431
4432 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004433 // TODO: make this consistent in early phases of code:
4434 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4435 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4436 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004437 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004438 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004439 int dummySize;
4440 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4441 if (componentAlignment <= 4)
4442 memberAlignment = componentAlignment;
4443 }
4444
4445 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004446 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004447
4448 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004449 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4450 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004451 glslang::RoundToPow2(currentOffset, 16);
4452
John Kessenich5e4b1242015-08-06 22:53:06 -06004453 nextOffset = currentOffset + memberSize;
4454}
4455
David Netoa901ffe2016-06-08 14:11:40 +01004456void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004457{
David Netoa901ffe2016-06-08 14:11:40 +01004458 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4459 switch (glslangBuiltIn)
4460 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004461 case glslang::EbvPointSize:
4462#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004463 case glslang::EbvClipDistance:
4464 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004465 case glslang::EbvViewportMaskNV:
4466 case glslang::EbvSecondaryPositionNV:
4467 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004468 case glslang::EbvPositionPerViewNV:
4469 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004470 case glslang::EbvTaskCountNV:
4471 case glslang::EbvPrimitiveCountNV:
4472 case glslang::EbvPrimitiveIndicesNV:
4473 case glslang::EbvClipDistancePerViewNV:
4474 case glslang::EbvCullDistancePerViewNV:
4475 case glslang::EbvLayerPerViewNV:
4476 case glslang::EbvMeshViewCountNV:
4477 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004478#endif
David Netoa901ffe2016-06-08 14:11:40 +01004479 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4480 // Alternately, we could just call this for any glslang built-in, since the
4481 // capability already guards against duplicates.
4482 TranslateBuiltInDecoration(glslangBuiltIn, false);
4483 break;
4484 default:
4485 // Capabilities were already generated when the struct was declared.
4486 break;
4487 }
John Kessenichebb50532016-05-16 19:22:05 -06004488}
4489
John Kessenich6fccb3c2016-09-19 16:01:41 -06004490bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004491{
John Kessenicheee9d532016-09-19 18:09:30 -06004492 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004493}
4494
John Kessenichd41993d2017-09-10 15:21:05 -06004495// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004496// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4497// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004498bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004499{
John Kessenich6a14f782017-12-04 02:48:10 -07004500 assert(qualifier == glslang::EvqIn ||
4501 qualifier == glslang::EvqOut ||
4502 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004503 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004504 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004505 return qualifier != glslang::EvqConstReadOnly &&
4506 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004507}
4508
4509// Is parameter pass-by-original?
4510bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4511 bool implicitThisParam)
4512{
4513 if (implicitThisParam) // implicit this
4514 return true;
4515 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004516 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004517 return paramType.containsOpaque() || // sampler, etc.
4518 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4519}
4520
John Kessenich140f3df2015-06-26 16:58:36 -06004521// Make all the functions, skeletally, without actually visiting their bodies.
4522void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4523{
John Kessenich8985fc92020-03-03 10:25:07 -07004524 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4525 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004526 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4527 if (paramPrecision != spv::NoPrecision)
4528 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004529 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004530 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004531 // Original and non-writable params pass the pointer directly and
4532 // use restrict/aliased, others are stored to a pointer in Function
4533 // memory and use RestrictPointer/AliasedPointer.
4534 if (originalParam(type.getQualifier().storage, type, false) ||
4535 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004536 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4537 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004538 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004539 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4540 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004541 }
4542 }
John Kessenichfad62972017-07-18 02:35:46 -06004543 };
4544
John Kessenich140f3df2015-06-26 16:58:36 -06004545 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4546 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004547 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004548 continue;
4549
4550 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004551 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004552 //
qining25262b32016-05-06 17:25:16 -04004553 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004554 // function. What it is an address of varies:
4555 //
John Kessenich4bf71552016-09-02 11:20:21 -06004556 // - "in" parameters not marked as "const" can be written to without modifying the calling
4557 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004558 //
4559 // - "const in" parameters can just be the r-value, as no writes need occur.
4560 //
John Kessenich4bf71552016-09-02 11:20:21 -06004561 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4562 // 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 -06004563
4564 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004565 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004566 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4567
John Kessenich155d3512019-08-08 23:29:20 -06004568#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004569 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4570 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004571#else
4572 bool implicitThis = false;
4573#endif
John Kessenich37789792017-03-21 23:56:40 -06004574
John Kessenichfad62972017-07-18 02:35:46 -06004575 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004576 for (int p = 0; p < (int)parameters.size(); ++p) {
4577 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4578 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004579 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004580 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004581 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004582 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4583 else
John Kessenich4bf71552016-09-02 11:20:21 -06004584 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004585 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004586 paramTypes.push_back(typeId);
4587 }
4588
4589 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004590 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4591 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004592 glslFunction->getName().c_str(), paramTypes,
4593 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004594 if (implicitThis)
4595 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004596
4597 // Track function to emit/call later
4598 functionMap[glslFunction->getName().c_str()] = function;
4599
4600 // Set the parameter id's
4601 for (int p = 0; p < (int)parameters.size(); ++p) {
4602 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4603 // give a name too
4604 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004605
4606 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004607 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004608 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004609 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004610 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004611 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004612 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004613 }
4614 }
4615}
4616
4617// Process all the initializers, while skipping the functions and link objects
4618void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4619{
4620 builder.setBuildPoint(shaderEntry->getLastBlock());
4621 for (int i = 0; i < (int)initializers.size(); ++i) {
4622 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004623 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4624 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004625
4626 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004627 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004628 initializer->traverse(this);
4629 }
4630 }
4631}
4632
4633// Process all the functions, while skipping initializers.
4634void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4635{
4636 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4637 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004638 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004639 node->traverse(this);
4640 }
4641}
4642
4643void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4644{
qining25262b32016-05-06 17:25:16 -04004645 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004646 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004647 currentFunction = functionMap[node->getName().c_str()];
4648 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004649 builder.setBuildPoint(functionBlock);
4650}
4651
John Kessenich8985fc92020-03-03 10:25:07 -07004652void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4653 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004654{
Rex Xufc618912015-09-09 16:42:49 +08004655 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004656
4657 glslang::TSampler sampler = {};
4658 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004659#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004660 bool f16ShadowCompare = false;
4661#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004662 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004663 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4664 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004665#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004666 f16ShadowCompare = sampler.shadow &&
4667 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004668#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004669 }
4670
John Kessenich140f3df2015-06-26 16:58:36 -06004671 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4672 builder.clearAccessChain();
4673 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004674
John Kessenicha28f7a72019-08-06 07:00:58 -06004675#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004676 // Special case l-value operands
4677 bool lvalue = false;
4678 switch (node.getOp()) {
4679 case glslang::EOpImageAtomicAdd:
4680 case glslang::EOpImageAtomicMin:
4681 case glslang::EOpImageAtomicMax:
4682 case glslang::EOpImageAtomicAnd:
4683 case glslang::EOpImageAtomicOr:
4684 case glslang::EOpImageAtomicXor:
4685 case glslang::EOpImageAtomicExchange:
4686 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004687 case glslang::EOpImageAtomicLoad:
4688 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004689 if (i == 0)
4690 lvalue = true;
4691 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004692 case glslang::EOpSparseImageLoad:
4693 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4694 lvalue = true;
4695 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004696 case glslang::EOpSparseTexture:
4697 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4698 lvalue = true;
4699 break;
4700 case glslang::EOpSparseTextureClamp:
4701 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4702 lvalue = true;
4703 break;
4704 case glslang::EOpSparseTextureLod:
4705 case glslang::EOpSparseTextureOffset:
4706 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4707 lvalue = true;
4708 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004709 case glslang::EOpSparseTextureFetch:
4710 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4711 lvalue = true;
4712 break;
4713 case glslang::EOpSparseTextureFetchOffset:
4714 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4715 lvalue = true;
4716 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004717 case glslang::EOpSparseTextureLodOffset:
4718 case glslang::EOpSparseTextureGrad:
4719 case glslang::EOpSparseTextureOffsetClamp:
4720 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4721 lvalue = true;
4722 break;
4723 case glslang::EOpSparseTextureGradOffset:
4724 case glslang::EOpSparseTextureGradClamp:
4725 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4726 lvalue = true;
4727 break;
4728 case glslang::EOpSparseTextureGradOffsetClamp:
4729 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4730 lvalue = true;
4731 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004732 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004733 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4734 lvalue = true;
4735 break;
4736 case glslang::EOpSparseTextureGatherOffset:
4737 case glslang::EOpSparseTextureGatherOffsets:
4738 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4739 lvalue = true;
4740 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004741 case glslang::EOpSparseTextureGatherLod:
4742 if (i == 3)
4743 lvalue = true;
4744 break;
4745 case glslang::EOpSparseTextureGatherLodOffset:
4746 case glslang::EOpSparseTextureGatherLodOffsets:
4747 if (i == 4)
4748 lvalue = true;
4749 break;
Rex Xu129799a2017-07-05 17:23:28 +08004750 case glslang::EOpSparseImageLoadLod:
4751 if (i == 3)
4752 lvalue = true;
4753 break;
Chao Chen3a137962018-09-19 11:41:27 -07004754 case glslang::EOpImageSampleFootprintNV:
4755 if (i == 4)
4756 lvalue = true;
4757 break;
4758 case glslang::EOpImageSampleFootprintClampNV:
4759 case glslang::EOpImageSampleFootprintLodNV:
4760 if (i == 5)
4761 lvalue = true;
4762 break;
4763 case glslang::EOpImageSampleFootprintGradNV:
4764 if (i == 6)
4765 lvalue = true;
4766 break;
4767 case glslang::EOpImageSampleFootprintGradClampNV:
4768 if (i == 7)
4769 lvalue = true;
4770 break;
Rex Xufc618912015-09-09 16:42:49 +08004771 default:
4772 break;
4773 }
4774
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004775 if (lvalue) {
greg-lunarg639f5462020-11-12 11:10:07 -07004776 spv::Id lvalue_id = builder.accessChainGetLValue();
4777 arguments.push_back(lvalue_id);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004778 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
greg-lunarg639f5462020-11-12 11:10:07 -07004779 builder.addDecoration(lvalue_id, TranslateNonUniformDecoration(lvalueCoherentFlags));
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004780 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4781 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004782#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004783 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004784 }
4785}
4786
John Kessenichfc51d282015-08-19 13:34:18 -06004787void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004788{
John Kessenichfc51d282015-08-19 13:34:18 -06004789 builder.clearAccessChain();
4790 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004791 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004792}
John Kessenich140f3df2015-06-26 16:58:36 -06004793
John Kessenichfc51d282015-08-19 13:34:18 -06004794spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4795{
John Kesseniche485c7a2017-05-31 18:50:53 -06004796 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004797 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004798
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004799 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004800
John Kessenichfc51d282015-08-19 13:34:18 -06004801 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004802
John Kessenichf43c7392019-03-31 10:51:57 -06004803 const glslang::TType &imageType = node->getAsAggregate()
4804 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4805 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004806 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004807#ifdef GLSLANG_WEB
4808 const bool f16ShadowCompare = false;
4809#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004810 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004811 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4812 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004813#endif
4814
John Kessenichf43c7392019-03-31 10:51:57 -06004815 const auto signExtensionMask = [&]() {
4816 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4817 if (sampler.type == glslang::EbtUint)
4818 return spv::ImageOperandsZeroExtendMask;
4819 else if (sampler.type == glslang::EbtInt)
4820 return spv::ImageOperandsSignExtendMask;
4821 }
4822 return spv::ImageOperandsMaskNone;
4823 };
4824
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004825 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4826
John Kessenichfc51d282015-08-19 13:34:18 -06004827 std::vector<spv::Id> arguments;
4828 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004829 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004830 else
4831 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004832 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004833
4834 spv::Builder::TextureParameters params = { };
4835 params.sampler = arguments[0];
4836
Rex Xu04db3f52015-09-16 11:44:02 +08004837 glslang::TCrackedTextureOp cracked;
4838 node->crackTexture(sampler, cracked);
4839
amhagan05506bb2017-06-13 16:53:02 -04004840 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004841
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004842 if (builder.isSampledImage(params.sampler) &&
4843 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4844 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4845 if (imageType.getQualifier().isNonUniform()) {
4846 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4847 }
4848 }
John Kessenichfc51d282015-08-19 13:34:18 -06004849 // Check for queries
4850 if (cracked.query) {
4851 switch (node->getOp()) {
4852 case glslang::EOpImageQuerySize:
4853 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004854 if (arguments.size() > 1) {
4855 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004856 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004857 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004858 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004859#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004860 case glslang::EOpImageQuerySamples:
4861 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004862 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004863 case glslang::EOpTextureQueryLod:
4864 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004865 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004866 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004867 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004868 case glslang::EOpSparseTexelsResident:
4869 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004870#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004871 default:
4872 assert(0);
4873 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004874 }
John Kessenich140f3df2015-06-26 16:58:36 -06004875 }
4876
LoopDawg4425f242018-02-18 11:40:01 -07004877 int components = node->getType().getVectorSize();
4878
4879 if (node->getOp() == glslang::EOpTextureFetch) {
4880 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4881 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4882 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4883 // here around e.g. which ones return scalars or other types.
4884 components = 4;
4885 }
4886
4887 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4888
4889 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4890
Rex Xufc618912015-09-09 16:42:49 +08004891 // Check for image functions other than queries
4892 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004893 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004894 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004895 spv::IdImmediate image = { true, *(opIt++) };
4896 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004897
4898 // Handle subpass operations
4899 // TODO: GLSL should change to have the "MS" only on the type rather than the
4900 // built-in function.
4901 if (cracked.subpass) {
4902 // add on the (0,0) coordinate
4903 spv::Id zero = builder.makeIntConstant(0);
4904 std::vector<spv::Id> comps;
4905 comps.push_back(zero);
4906 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004907 spv::IdImmediate coord = { true,
4908 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4909 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004910 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4911 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004912 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004913 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4914 }
4915 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004916 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004917 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004918 spv::IdImmediate imageOperand = { true, *(opIt++) };
4919 operands.push_back(imageOperand);
4920 }
John Kessenich6c292d32016-02-15 20:58:50 -07004921 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004922 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4923 builder.setPrecision(result, precision);
4924 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004925 }
4926
John Kessenich149afc32018-08-14 13:31:43 -06004927 spv::IdImmediate coord = { true, *(opIt++) };
4928 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004929 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004930 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004931 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004932 mask = mask | spv::ImageOperandsSampleMask;
4933 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004934 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004935 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4936 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004937 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004938 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004939 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4940 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004941 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004942 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004943 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4944 operands.push_back(imageOperands);
4945 }
4946 if (mask & spv::ImageOperandsSampleMask) {
4947 spv::IdImmediate imageOperand = { true, *opIt++ };
4948 operands.push_back(imageOperand);
4949 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004950 if (mask & spv::ImageOperandsLodMask) {
4951 spv::IdImmediate imageOperand = { true, *opIt++ };
4952 operands.push_back(imageOperand);
4953 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004954 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004955 spv::IdImmediate imageOperand = { true,
4956 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004957 operands.push_back(imageOperand);
4958 }
4959
John Kessenich149afc32018-08-14 13:31:43 -06004960 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004961 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004962
John Kessenich149afc32018-08-14 13:31:43 -06004963 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004964 builder.setPrecision(result[0], precision);
4965
4966 // If needed, add a conversion constructor to the proper size.
4967 if (components != node->getType().getVectorSize())
4968 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4969
4970 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004971 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004972
Jeff Bolz36831c92018-09-05 10:11:41 -05004973 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004974 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004975 spv::IdImmediate texel = { true, *(opIt + 1) };
4976 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004977 } else {
4978 spv::IdImmediate texel = { true, *opIt };
4979 operands.push_back(texel);
4980 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004981
4982 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004983 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004984 mask = mask | spv::ImageOperandsSampleMask;
4985 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004986 if (cracked.lod) {
4987 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4988 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4989 mask = mask | spv::ImageOperandsLodMask;
4990 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004991 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4992 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004993 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004994 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004995 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4996 operands.push_back(imageOperands);
4997 }
4998 if (mask & spv::ImageOperandsSampleMask) {
4999 spv::IdImmediate imageOperand = { true, *opIt++ };
5000 operands.push_back(imageOperand);
5001 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005002 if (mask & spv::ImageOperandsLodMask) {
5003 spv::IdImmediate imageOperand = { true, *opIt++ };
5004 operands.push_back(imageOperand);
5005 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005006 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06005007 spv::IdImmediate imageOperand = { true,
5008 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005009 operands.push_back(imageOperand);
5010 }
5011
John Kessenich56bab042015-09-16 10:54:31 -06005012 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06005013 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07005014 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06005015 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06005016 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
5017 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08005018 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06005019 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08005020 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
5021
Jeff Bolz36831c92018-09-05 10:11:41 -05005022 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005023 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005024 mask = mask | spv::ImageOperandsSampleMask;
5025 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005026 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08005027 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
5028 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
5029
Jeff Bolz36831c92018-09-05 10:11:41 -05005030 mask = mask | spv::ImageOperandsLodMask;
5031 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005032 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
5033 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06005034 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06005035 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05005036 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06005037 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05005038 }
5039 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06005040 spv::IdImmediate imageOperand = { true, *opIt++ };
5041 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05005042 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005043 if (mask & spv::ImageOperandsLodMask) {
5044 spv::IdImmediate imageOperand = { true, *opIt++ };
5045 operands.push_back(imageOperand);
5046 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005047 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07005048 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
5049 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005050 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08005051 }
5052
5053 // Create the return type that was a special structure
5054 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06005055 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08005056 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
5057 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
5058
5059 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
5060
5061 // Decode the return type
5062 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
5063 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07005064 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08005065 // Process image atomic operations
5066
5067 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5068 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005069 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005070 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005071 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005072
Jeff Bolz36831c92018-09-05 10:11:41 -05005073 spv::Id resultTypeId;
5074 // imageAtomicStore has a void return type so base the pointer type on
5075 // the type of the value operand.
5076 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005077 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005078 } else {
5079 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5080 }
John Kessenich56bab042015-09-16 10:54:31 -06005081 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005082 if (imageType.getQualifier().nonUniform) {
5083 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5084 }
Rex Xufc618912015-09-09 16:42:49 +08005085
5086 std::vector<spv::Id> operands;
5087 operands.push_back(pointer);
5088 for (; opIt != arguments.end(); ++opIt)
5089 operands.push_back(*opIt);
5090
John Kessenich8985fc92020-03-03 10:25:07 -07005091 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5092 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005093 }
5094 }
5095
John Kessenicha28f7a72019-08-06 07:00:58 -06005096#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005097 // Check for fragment mask functions other than queries
5098 if (cracked.fragMask) {
5099 assert(sampler.ms);
5100
5101 auto opIt = arguments.begin();
5102 std::vector<spv::Id> operands;
5103
amhagan05506bb2017-06-13 16:53:02 -04005104 operands.push_back(params.sampler);
5105 ++opIt;
5106
5107 if (sampler.isSubpass()) {
5108 // add on the (0,0) coordinate
5109 spv::Id zero = builder.makeIntConstant(0);
5110 std::vector<spv::Id> comps;
5111 comps.push_back(zero);
5112 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005113 operands.push_back(builder.makeCompositeConstant(
5114 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005115 }
5116
5117 for (; opIt != arguments.end(); ++opIt)
5118 operands.push_back(*opIt);
5119
5120 spv::Op fragMaskOp = spv::OpNop;
5121 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5122 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5123 else if (node->getOp() == glslang::EOpFragmentFetch)
5124 fragMaskOp = spv::OpFragmentFetchAMD;
5125
5126 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5127 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5128 return builder.createOp(fragMaskOp, resultType(), operands);
5129 }
5130#endif
5131
Rex Xufc618912015-09-09 16:42:49 +08005132 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005133 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005134 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005135 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005136
John Kessenichfc51d282015-08-19 13:34:18 -06005137 // check for bias argument
5138 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005139 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005140 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005141 if (cracked.gather)
5142 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005143
5144 if (f16ShadowCompare)
5145 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005146 if (cracked.offset)
5147 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005148 else if (cracked.offsets)
5149 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005150 if (cracked.grad)
5151 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005152 if (cracked.lodClamp)
5153 ++nonBiasArgCount;
5154 if (sparse)
5155 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005156 if (imageFootprint)
5157 //Following three extra arguments
5158 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5159 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005160 if ((int)arguments.size() > nonBiasArgCount)
5161 bias = true;
5162 }
5163
John Kessenicha28f7a72019-08-06 07:00:58 -06005164#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005165 if (cracked.gather) {
5166 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5167 if (bias || cracked.lod ||
5168 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5169 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005170 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005171 }
5172 }
5173#endif
5174
John Kessenichfc51d282015-08-19 13:34:18 -06005175 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005176
John Kessenichfc51d282015-08-19 13:34:18 -06005177 params.coords = arguments[1];
5178 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005179 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005180
5181 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005182 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005183 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005184 ++extraArgs;
5185 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005186 params.Dref = arguments[2];
5187 ++extraArgs;
5188 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005189 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005190 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005191 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005192 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005193 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005194 dRefComp = builder.getNumComponents(params.coords) - 1;
5195 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005196 params.Dref = builder.createCompositeExtract(params.coords,
5197 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005198 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005199
5200 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005201 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005202 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005203 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005204 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5205 !(glslangIntermediate->getStage() == EShLangCompute &&
5206 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005207 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5208 noImplicitLod = true;
5209 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005210
5211 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005212 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005213 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005214 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005215 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005216
5217 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005218 if (cracked.grad) {
5219 params.gradX = arguments[2 + extraArgs];
5220 params.gradY = arguments[3 + extraArgs];
5221 extraArgs += 2;
5222 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005223
5224 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005225 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005226 params.offset = arguments[2 + extraArgs];
5227 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005228 } else if (cracked.offsets) {
5229 params.offsets = arguments[2 + extraArgs];
5230 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005231 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005232
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005233#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005234 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005235 if (cracked.lodClamp) {
5236 params.lodClamp = arguments[2 + extraArgs];
5237 ++extraArgs;
5238 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005239 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005240 if (sparse) {
5241 params.texelOut = arguments[2 + extraArgs];
5242 ++extraArgs;
5243 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005244 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005245 if (cracked.gather && ! sampler.shadow) {
5246 // default component is 0, if missing, otherwise an argument
5247 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005248 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005249 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005250 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005251 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005252 }
Chao Chen3a137962018-09-19 11:41:27 -07005253 spv::Id resultStruct = spv::NoResult;
5254 if (imageFootprint) {
5255 //Following three extra arguments
5256 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5257 params.granularity = arguments[2 + extraArgs];
5258 params.coarse = arguments[3 + extraArgs];
5259 resultStruct = arguments[4 + extraArgs];
5260 extraArgs += 3;
5261 }
5262#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005263 // bias
5264 if (bias) {
5265 params.bias = arguments[2 + extraArgs];
5266 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005267 }
John Kessenichfc51d282015-08-19 13:34:18 -06005268
John Kessenicha28f7a72019-08-06 07:00:58 -06005269#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005270 if (imageFootprint) {
5271 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5272 builder.addCapability(spv::CapabilityImageFootprintNV);
5273
5274
5275 //resultStructType(OpenGL type) contains 5 elements:
5276 //struct gl_TextureFootprint2DNV {
5277 // uvec2 anchor;
5278 // uvec2 offset;
5279 // uvec2 mask;
5280 // uint lod;
5281 // uint granularity;
5282 //};
5283 //or
5284 //struct gl_TextureFootprint3DNV {
5285 // uvec3 anchor;
5286 // uvec3 offset;
5287 // uvec2 mask;
5288 // uint lod;
5289 // uint granularity;
5290 //};
5291 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5292 assert(builder.isStructType(resultStructType));
5293
5294 //resType (SPIR-V type) contains 6 elements:
5295 //Member 0 must be a Boolean type scalar(LOD),
5296 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5297 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5298 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5299 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5300 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5301 std::vector<spv::Id> members;
5302 members.push_back(resultType());
5303 for (int i = 0; i < 5; i++) {
5304 members.push_back(builder.getContainedTypeId(resultStructType, i));
5305 }
5306 spv::Id resType = builder.makeStructType(members, "ResType");
5307
5308 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005309 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5310 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005311
5312 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5313 for (int i = 0; i < 5; i++) {
5314 builder.clearAccessChain();
5315 builder.setAccessChainLValue(resultStruct);
5316
5317 //Accessing to a struct we created, no coherent flag is set
5318 spv::Builder::AccessChain::CoherentFlags flags;
5319 flags.clear();
5320
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005321 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005322 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005323 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005324 }
5325 return builder.createCompositeExtract(res, resultType(), 0);
5326 }
5327#endif
5328
John Kessenich65336482016-06-16 14:06:26 -06005329 // projective component (might not to move)
5330 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5331 // are divided by the last component of P."
5332 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5333 // unused components will appear after all used components."
5334 if (cracked.proj) {
5335 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5336 int projTargetComp;
5337 switch (sampler.dim) {
5338 case glslang::Esd1D: projTargetComp = 1; break;
5339 case glslang::Esd2D: projTargetComp = 2; break;
5340 case glslang::EsdRect: projTargetComp = 2; break;
5341 default: projTargetComp = projSourceComp; break;
5342 }
5343 // copy the projective coordinate if we have to
5344 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005345 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005346 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005347 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005348 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005349 }
5350 }
5351
John Kessenichf8d1d742019-10-21 06:55:11 -06005352#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005353 // nonprivate
5354 if (imageType.getQualifier().nonprivate) {
5355 params.nonprivate = true;
5356 }
5357
5358 // volatile
5359 if (imageType.getQualifier().volatil) {
5360 params.volatil = true;
5361 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005362#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005363
St0fFa1184dd2018-04-09 21:08:14 +02005364 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005365 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5366 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005367 );
LoopDawg4425f242018-02-18 11:40:01 -07005368
5369 if (components != node->getType().getVectorSize())
5370 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5371
5372 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005373}
5374
5375spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5376{
5377 // Grab the function's pointer from the previously created function
5378 spv::Function* function = functionMap[node->getName().c_str()];
5379 if (! function)
5380 return 0;
5381
5382 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5383 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5384
5385 // See comments in makeFunctions() for details about the semantics for parameter passing.
5386 //
5387 // These imply we need a four step process:
5388 // 1. Evaluate the arguments
5389 // 2. Allocate and make copies of in, out, and inout arguments
5390 // 3. Make the call
5391 // 4. Copy back the results
5392
John Kessenichd3ed90b2018-05-04 11:43:03 -06005393 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005394 std::vector<spv::Builder::AccessChain> lValues;
5395 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005396 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005397 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005398 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005399 // build l-value
5400 builder.clearAccessChain();
5401 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005402 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005403 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005404 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005405 // save l-value
5406 lValues.push_back(builder.getAccessChain());
5407 } else {
5408 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005409 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005410 }
5411 }
5412
5413 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5414 // copy the original into that space.
5415 //
5416 // Also, build up the list of actual arguments to pass in for the call
5417 int lValueCount = 0;
5418 int rValueCount = 0;
5419 std::vector<spv::Id> spvArgs;
5420 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5421 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005422 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005423 builder.setAccessChain(lValues[lValueCount]);
5424 arg = builder.accessChainGetLValue();
5425 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005426 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005427 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005428 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005429 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005430 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5431 // need to copy the input into output space
5432 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005433 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005434 builder.clearAccessChain();
5435 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005436 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005437 }
5438 ++lValueCount;
5439 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005440 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005441 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005442 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005443 {
John Kessenich435dd802020-06-30 01:27:08 -06005444 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005445 builder.clearAccessChain();
5446 builder.setAccessChainLValue(argCopy);
5447 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005448 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005449 } else
5450 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005451 ++rValueCount;
5452 }
5453 spvArgs.push_back(arg);
5454 }
5455
5456 // 3. Make the call.
5457 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005458 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
greg-lunarg639f5462020-11-12 11:10:07 -07005459 builder.addDecoration(result, TranslateNonUniformDecoration(node->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005460
5461 // 4. Copy back out an "out" arguments.
5462 lValueCount = 0;
5463 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005464 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005465 ++lValueCount;
5466 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005467 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005468 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
greg-lunarg639f5462020-11-12 11:10:07 -07005469 builder.addDecoration(copy, TranslateNonUniformDecoration(argTypes[a]->getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06005470 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005471 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005472 }
5473 ++lValueCount;
5474 }
5475 }
5476
5477 return result;
5478}
5479
5480// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005481spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005482 spv::Id typeId, spv::Id left, spv::Id right,
5483 glslang::TBasicType typeProxy, bool reduceComparison)
5484{
John Kessenich66011cb2018-03-06 16:12:04 -07005485 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5486 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005487 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005488
5489 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005490 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005491 bool comparison = false;
5492
5493 switch (op) {
5494 case glslang::EOpAdd:
5495 case glslang::EOpAddAssign:
5496 if (isFloat)
5497 binOp = spv::OpFAdd;
5498 else
5499 binOp = spv::OpIAdd;
5500 break;
5501 case glslang::EOpSub:
5502 case glslang::EOpSubAssign:
5503 if (isFloat)
5504 binOp = spv::OpFSub;
5505 else
5506 binOp = spv::OpISub;
5507 break;
5508 case glslang::EOpMul:
5509 case glslang::EOpMulAssign:
5510 if (isFloat)
5511 binOp = spv::OpFMul;
5512 else
5513 binOp = spv::OpIMul;
5514 break;
5515 case glslang::EOpVectorTimesScalar:
5516 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005517 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005518 if (builder.isVector(right))
5519 std::swap(left, right);
5520 assert(builder.isScalar(right));
5521 needMatchingVectors = false;
5522 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005523 } else if (isFloat)
5524 binOp = spv::OpFMul;
5525 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005526 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005527 break;
5528 case glslang::EOpVectorTimesMatrix:
5529 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005530 binOp = spv::OpVectorTimesMatrix;
5531 break;
5532 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005533 binOp = spv::OpMatrixTimesVector;
5534 break;
5535 case glslang::EOpMatrixTimesScalar:
5536 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005537 binOp = spv::OpMatrixTimesScalar;
5538 break;
5539 case glslang::EOpMatrixTimesMatrix:
5540 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005541 binOp = spv::OpMatrixTimesMatrix;
5542 break;
5543 case glslang::EOpOuterProduct:
5544 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005545 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005546 break;
5547
5548 case glslang::EOpDiv:
5549 case glslang::EOpDivAssign:
5550 if (isFloat)
5551 binOp = spv::OpFDiv;
5552 else if (isUnsigned)
5553 binOp = spv::OpUDiv;
5554 else
5555 binOp = spv::OpSDiv;
5556 break;
5557 case glslang::EOpMod:
5558 case glslang::EOpModAssign:
5559 if (isFloat)
5560 binOp = spv::OpFMod;
5561 else if (isUnsigned)
5562 binOp = spv::OpUMod;
5563 else
5564 binOp = spv::OpSMod;
5565 break;
5566 case glslang::EOpRightShift:
5567 case glslang::EOpRightShiftAssign:
5568 if (isUnsigned)
5569 binOp = spv::OpShiftRightLogical;
5570 else
5571 binOp = spv::OpShiftRightArithmetic;
5572 break;
5573 case glslang::EOpLeftShift:
5574 case glslang::EOpLeftShiftAssign:
5575 binOp = spv::OpShiftLeftLogical;
5576 break;
5577 case glslang::EOpAnd:
5578 case glslang::EOpAndAssign:
5579 binOp = spv::OpBitwiseAnd;
5580 break;
5581 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005582 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005583 binOp = spv::OpLogicalAnd;
5584 break;
5585 case glslang::EOpInclusiveOr:
5586 case glslang::EOpInclusiveOrAssign:
5587 binOp = spv::OpBitwiseOr;
5588 break;
5589 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005590 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005591 binOp = spv::OpLogicalOr;
5592 break;
5593 case glslang::EOpExclusiveOr:
5594 case glslang::EOpExclusiveOrAssign:
5595 binOp = spv::OpBitwiseXor;
5596 break;
5597 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005598 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005599 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005600 break;
5601
Ian Romanickb3bd4022019-01-21 08:57:25 -08005602 case glslang::EOpAbsDifference:
5603 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5604 break;
5605
5606 case glslang::EOpAddSaturate:
5607 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5608 break;
5609
5610 case glslang::EOpSubSaturate:
5611 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5612 break;
5613
5614 case glslang::EOpAverage:
5615 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5616 break;
5617
5618 case glslang::EOpAverageRounded:
5619 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5620 break;
5621
5622 case glslang::EOpMul32x16:
5623 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5624 break;
5625
John Kessenich140f3df2015-06-26 16:58:36 -06005626 case glslang::EOpLessThan:
5627 case glslang::EOpGreaterThan:
5628 case glslang::EOpLessThanEqual:
5629 case glslang::EOpGreaterThanEqual:
5630 case glslang::EOpEqual:
5631 case glslang::EOpNotEqual:
5632 case glslang::EOpVectorEqual:
5633 case glslang::EOpVectorNotEqual:
5634 comparison = true;
5635 break;
5636 default:
5637 break;
5638 }
5639
John Kessenich7c1aa102015-10-15 13:29:11 -06005640 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005641 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005642 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005643 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5644 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005645 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005646
5647 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005648 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005649 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005650
qining25262b32016-05-06 17:25:16 -04005651 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005652 decorations.addNoContraction(builder, result);
5653 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005654 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005655 }
5656
5657 if (! comparison)
5658 return 0;
5659
John Kessenich7c1aa102015-10-15 13:29:11 -06005660 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005661
John Kessenich4583b612016-08-07 19:14:22 -06005662 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005663 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5664 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005665 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005666 return result;
5667 }
John Kessenich140f3df2015-06-26 16:58:36 -06005668
5669 switch (op) {
5670 case glslang::EOpLessThan:
5671 if (isFloat)
5672 binOp = spv::OpFOrdLessThan;
5673 else if (isUnsigned)
5674 binOp = spv::OpULessThan;
5675 else
5676 binOp = spv::OpSLessThan;
5677 break;
5678 case glslang::EOpGreaterThan:
5679 if (isFloat)
5680 binOp = spv::OpFOrdGreaterThan;
5681 else if (isUnsigned)
5682 binOp = spv::OpUGreaterThan;
5683 else
5684 binOp = spv::OpSGreaterThan;
5685 break;
5686 case glslang::EOpLessThanEqual:
5687 if (isFloat)
5688 binOp = spv::OpFOrdLessThanEqual;
5689 else if (isUnsigned)
5690 binOp = spv::OpULessThanEqual;
5691 else
5692 binOp = spv::OpSLessThanEqual;
5693 break;
5694 case glslang::EOpGreaterThanEqual:
5695 if (isFloat)
5696 binOp = spv::OpFOrdGreaterThanEqual;
5697 else if (isUnsigned)
5698 binOp = spv::OpUGreaterThanEqual;
5699 else
5700 binOp = spv::OpSGreaterThanEqual;
5701 break;
5702 case glslang::EOpEqual:
5703 case glslang::EOpVectorEqual:
5704 if (isFloat)
5705 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005706 else if (isBool)
5707 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005708 else
5709 binOp = spv::OpIEqual;
5710 break;
5711 case glslang::EOpNotEqual:
5712 case glslang::EOpVectorNotEqual:
5713 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005714 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005715 else if (isBool)
5716 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005717 else
5718 binOp = spv::OpINotEqual;
5719 break;
5720 default:
5721 break;
5722 }
5723
qining25262b32016-05-06 17:25:16 -04005724 if (binOp != spv::OpNop) {
5725 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005726 decorations.addNoContraction(builder, result);
5727 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005728 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005729 }
John Kessenich140f3df2015-06-26 16:58:36 -06005730
5731 return 0;
5732}
5733
John Kessenich04bb8a02015-12-12 12:28:14 -07005734//
5735// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5736// These can be any of:
5737//
5738// matrix * scalar
5739// scalar * matrix
5740// matrix * matrix linear algebraic
5741// matrix * vector
5742// vector * matrix
5743// matrix * matrix componentwise
5744// matrix op matrix op in {+, -, /}
5745// matrix op scalar op in {+, -, /}
5746// scalar op matrix op in {+, -, /}
5747//
John Kessenichead86222018-03-28 18:01:20 -06005748spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5749 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005750{
5751 bool firstClass = true;
5752
5753 // First, handle first-class matrix operations (* and matrix/scalar)
5754 switch (op) {
5755 case spv::OpFDiv:
5756 if (builder.isMatrix(left) && builder.isScalar(right)) {
5757 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005758 spv::Id resultType = builder.getTypeId(right);
5759 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005760 op = spv::OpMatrixTimesScalar;
5761 } else
5762 firstClass = false;
5763 break;
5764 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005765 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005766 std::swap(left, right);
5767 assert(builder.isScalar(right));
5768 break;
5769 case spv::OpVectorTimesMatrix:
5770 assert(builder.isVector(left));
5771 assert(builder.isMatrix(right));
5772 break;
5773 case spv::OpMatrixTimesVector:
5774 assert(builder.isMatrix(left));
5775 assert(builder.isVector(right));
5776 break;
5777 case spv::OpMatrixTimesMatrix:
5778 assert(builder.isMatrix(left));
5779 assert(builder.isMatrix(right));
5780 break;
5781 default:
5782 firstClass = false;
5783 break;
5784 }
5785
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005786 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5787 firstClass = true;
5788
qining25262b32016-05-06 17:25:16 -04005789 if (firstClass) {
5790 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005791 decorations.addNoContraction(builder, result);
5792 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005793 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005794 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005795
LoopDawg592860c2016-06-09 08:57:35 -06005796 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005797 // The result type of all of them is the same type as the (a) matrix operand.
5798 // The algorithm is to:
5799 // - break the matrix(es) into vectors
5800 // - smear any scalar to a vector
5801 // - do vector operations
5802 // - make a matrix out the vector results
5803 switch (op) {
5804 case spv::OpFAdd:
5805 case spv::OpFSub:
5806 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005807 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005808 case spv::OpFMul:
5809 {
5810 // one time set up...
5811 bool leftMat = builder.isMatrix(left);
5812 bool rightMat = builder.isMatrix(right);
5813 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5814 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5815 spv::Id scalarType = builder.getScalarTypeId(typeId);
5816 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5817 std::vector<spv::Id> results;
5818 spv::Id smearVec = spv::NoResult;
5819 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005820 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005821 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005822 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005823
5824 // do each vector op
5825 for (unsigned int c = 0; c < numCols; ++c) {
5826 std::vector<unsigned int> indexes;
5827 indexes.push_back(c);
5828 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5829 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005830 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005831 decorations.addNoContraction(builder, result);
5832 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005833 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005834 }
5835
5836 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005837 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005838 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005839 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005840 }
5841 default:
5842 assert(0);
5843 return spv::NoResult;
5844 }
5845}
5846
John Kessenichead86222018-03-28 18:01:20 -06005847spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005848 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005849{
5850 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005851 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005852 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005853 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5854 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005855
5856 switch (op) {
5857 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005858 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005859 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005860 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005861 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005862 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005863 unaryOp = spv::OpSNegate;
5864 break;
5865
5866 case glslang::EOpLogicalNot:
5867 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005868 unaryOp = spv::OpLogicalNot;
5869 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005870 case glslang::EOpBitwiseNot:
5871 unaryOp = spv::OpNot;
5872 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005873
John Kessenich140f3df2015-06-26 16:58:36 -06005874 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005875 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005876 break;
5877 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005878 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005879 break;
5880 case glslang::EOpTranspose:
5881 unaryOp = spv::OpTranspose;
5882 break;
5883
5884 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005885 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005886 break;
5887 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005888 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005889 break;
5890 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005891 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005892 break;
5893 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005894 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005895 break;
5896 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005897 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005898 break;
5899 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005900 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005901 break;
5902 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005903 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005904 break;
5905 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005906 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005907 break;
5908
5909 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005910 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005911 break;
5912 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005913 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005914 break;
5915 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005916 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005917 break;
5918 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005919 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005920 break;
5921 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005922 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005923 break;
5924 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005925 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005926 break;
5927
5928 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005929 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005930 break;
5931 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005932 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005933 break;
5934
5935 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005936 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005937 break;
5938 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005939 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005940 break;
5941 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005942 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005943 break;
5944 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005945 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005946 break;
5947 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005948 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005949 break;
5950 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005951 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005952 break;
5953
5954 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005955 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005956 break;
5957 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005958 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005959 break;
5960 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005961 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005962 break;
5963 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005964 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005965 break;
5966 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005967 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005968 break;
5969 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005970 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005971 break;
5972
5973 case glslang::EOpIsNan:
5974 unaryOp = spv::OpIsNan;
5975 break;
5976 case glslang::EOpIsInf:
5977 unaryOp = spv::OpIsInf;
5978 break;
LoopDawg592860c2016-06-09 08:57:35 -06005979 case glslang::EOpIsFinite:
5980 unaryOp = spv::OpIsFinite;
5981 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005982
Rex Xucbc426e2015-12-15 16:03:10 +08005983 case glslang::EOpFloatBitsToInt:
5984 case glslang::EOpFloatBitsToUint:
5985 case glslang::EOpIntBitsToFloat:
5986 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005987 case glslang::EOpDoubleBitsToInt64:
5988 case glslang::EOpDoubleBitsToUint64:
5989 case glslang::EOpInt64BitsToDouble:
5990 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005991 case glslang::EOpFloat16BitsToInt16:
5992 case glslang::EOpFloat16BitsToUint16:
5993 case glslang::EOpInt16BitsToFloat16:
5994 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005995 unaryOp = spv::OpBitcast;
5996 break;
5997
John Kessenich140f3df2015-06-26 16:58:36 -06005998 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005999 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006000 break;
6001 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006002 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006003 break;
6004 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006005 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006006 break;
6007 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006008 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006009 break;
6010 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006011 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006012 break;
6013 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06006014 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06006015 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006016#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06006017 case glslang::EOpPackSnorm4x8:
6018 libCall = spv::GLSLstd450PackSnorm4x8;
6019 break;
6020 case glslang::EOpUnpackSnorm4x8:
6021 libCall = spv::GLSLstd450UnpackSnorm4x8;
6022 break;
6023 case glslang::EOpPackUnorm4x8:
6024 libCall = spv::GLSLstd450PackUnorm4x8;
6025 break;
6026 case glslang::EOpUnpackUnorm4x8:
6027 libCall = spv::GLSLstd450UnpackUnorm4x8;
6028 break;
6029 case glslang::EOpPackDouble2x32:
6030 libCall = spv::GLSLstd450PackDouble2x32;
6031 break;
6032 case glslang::EOpUnpackDouble2x32:
6033 libCall = spv::GLSLstd450UnpackDouble2x32;
6034 break;
John Kessenichb9197c82019-08-11 07:41:45 -06006035#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006036
Rex Xu8ff43de2016-04-22 16:51:45 +08006037 case glslang::EOpPackInt2x32:
6038 case glslang::EOpUnpackInt2x32:
6039 case glslang::EOpPackUint2x32:
6040 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07006041 case glslang::EOpPack16:
6042 case glslang::EOpPack32:
6043 case glslang::EOpPack64:
6044 case glslang::EOpUnpack32:
6045 case glslang::EOpUnpack16:
6046 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08006047 case glslang::EOpPackInt2x16:
6048 case glslang::EOpUnpackInt2x16:
6049 case glslang::EOpPackUint2x16:
6050 case glslang::EOpUnpackUint2x16:
6051 case glslang::EOpPackInt4x16:
6052 case glslang::EOpUnpackInt4x16:
6053 case glslang::EOpPackUint4x16:
6054 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006055 case glslang::EOpPackFloat2x16:
6056 case glslang::EOpUnpackFloat2x16:
6057 unaryOp = spv::OpBitcast;
6058 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006059
John Kessenich140f3df2015-06-26 16:58:36 -06006060 case glslang::EOpDPdx:
6061 unaryOp = spv::OpDPdx;
6062 break;
6063 case glslang::EOpDPdy:
6064 unaryOp = spv::OpDPdy;
6065 break;
6066 case glslang::EOpFwidth:
6067 unaryOp = spv::OpFwidth;
6068 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006069
John Kessenich140f3df2015-06-26 16:58:36 -06006070 case glslang::EOpAny:
6071 unaryOp = spv::OpAny;
6072 break;
6073 case glslang::EOpAll:
6074 unaryOp = spv::OpAll;
6075 break;
6076
6077 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006078 if (isFloat)
6079 libCall = spv::GLSLstd450FAbs;
6080 else
6081 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006082 break;
6083 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006084 if (isFloat)
6085 libCall = spv::GLSLstd450FSign;
6086 else
6087 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006088 break;
6089
John Kessenicha28f7a72019-08-06 07:00:58 -06006090#ifndef GLSLANG_WEB
6091 case glslang::EOpDPdxFine:
6092 unaryOp = spv::OpDPdxFine;
6093 break;
6094 case glslang::EOpDPdyFine:
6095 unaryOp = spv::OpDPdyFine;
6096 break;
6097 case glslang::EOpFwidthFine:
6098 unaryOp = spv::OpFwidthFine;
6099 break;
6100 case glslang::EOpDPdxCoarse:
6101 unaryOp = spv::OpDPdxCoarse;
6102 break;
6103 case glslang::EOpDPdyCoarse:
6104 unaryOp = spv::OpDPdyCoarse;
6105 break;
6106 case glslang::EOpFwidthCoarse:
6107 unaryOp = spv::OpFwidthCoarse;
6108 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006109 case glslang::EOpRayQueryProceed:
6110 unaryOp = spv::OpRayQueryProceedKHR;
6111 break;
6112 case glslang::EOpRayQueryGetRayTMin:
6113 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6114 break;
6115 case glslang::EOpRayQueryGetRayFlags:
6116 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6117 break;
6118 case glslang::EOpRayQueryGetWorldRayOrigin:
6119 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6120 break;
6121 case glslang::EOpRayQueryGetWorldRayDirection:
6122 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6123 break;
6124 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6125 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6126 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006127 case glslang::EOpInterpolateAtCentroid:
6128 if (typeProxy == glslang::EbtFloat16)
6129 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6130 libCall = spv::GLSLstd450InterpolateAtCentroid;
6131 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006132 case glslang::EOpAtomicCounterIncrement:
6133 case glslang::EOpAtomicCounterDecrement:
6134 case glslang::EOpAtomicCounter:
6135 {
6136 // Handle all of the atomics in one place, in createAtomicOperation()
6137 std::vector<spv::Id> operands;
6138 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006139 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006140 }
6141
John Kessenichfc51d282015-08-19 13:34:18 -06006142 case glslang::EOpBitFieldReverse:
6143 unaryOp = spv::OpBitReverse;
6144 break;
6145 case glslang::EOpBitCount:
6146 unaryOp = spv::OpBitCount;
6147 break;
6148 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006149 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006150 break;
6151 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006152 if (isUnsigned)
6153 libCall = spv::GLSLstd450FindUMsb;
6154 else
6155 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006156 break;
6157
Ian Romanickb3bd4022019-01-21 08:57:25 -08006158 case glslang::EOpCountLeadingZeros:
6159 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6160 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6161 unaryOp = spv::OpUCountLeadingZerosINTEL;
6162 break;
6163
6164 case glslang::EOpCountTrailingZeros:
6165 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6166 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6167 unaryOp = spv::OpUCountTrailingZerosINTEL;
6168 break;
6169
Rex Xu574ab042016-04-14 16:53:07 +08006170 case glslang::EOpBallot:
6171 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006172 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006173 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006174 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006175 case glslang::EOpMinInvocations:
6176 case glslang::EOpMaxInvocations:
6177 case glslang::EOpAddInvocations:
6178 case glslang::EOpMinInvocationsNonUniform:
6179 case glslang::EOpMaxInvocationsNonUniform:
6180 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006181 case glslang::EOpMinInvocationsInclusiveScan:
6182 case glslang::EOpMaxInvocationsInclusiveScan:
6183 case glslang::EOpAddInvocationsInclusiveScan:
6184 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6185 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6186 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6187 case glslang::EOpMinInvocationsExclusiveScan:
6188 case glslang::EOpMaxInvocationsExclusiveScan:
6189 case glslang::EOpAddInvocationsExclusiveScan:
6190 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6191 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6192 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006193 {
6194 std::vector<spv::Id> operands;
6195 operands.push_back(operand);
6196 return createInvocationsOperation(op, typeId, operands, typeProxy);
6197 }
John Kessenich66011cb2018-03-06 16:12:04 -07006198 case glslang::EOpSubgroupAll:
6199 case glslang::EOpSubgroupAny:
6200 case glslang::EOpSubgroupAllEqual:
6201 case glslang::EOpSubgroupBroadcastFirst:
6202 case glslang::EOpSubgroupBallot:
6203 case glslang::EOpSubgroupInverseBallot:
6204 case glslang::EOpSubgroupBallotBitCount:
6205 case glslang::EOpSubgroupBallotInclusiveBitCount:
6206 case glslang::EOpSubgroupBallotExclusiveBitCount:
6207 case glslang::EOpSubgroupBallotFindLSB:
6208 case glslang::EOpSubgroupBallotFindMSB:
6209 case glslang::EOpSubgroupAdd:
6210 case glslang::EOpSubgroupMul:
6211 case glslang::EOpSubgroupMin:
6212 case glslang::EOpSubgroupMax:
6213 case glslang::EOpSubgroupAnd:
6214 case glslang::EOpSubgroupOr:
6215 case glslang::EOpSubgroupXor:
6216 case glslang::EOpSubgroupInclusiveAdd:
6217 case glslang::EOpSubgroupInclusiveMul:
6218 case glslang::EOpSubgroupInclusiveMin:
6219 case glslang::EOpSubgroupInclusiveMax:
6220 case glslang::EOpSubgroupInclusiveAnd:
6221 case glslang::EOpSubgroupInclusiveOr:
6222 case glslang::EOpSubgroupInclusiveXor:
6223 case glslang::EOpSubgroupExclusiveAdd:
6224 case glslang::EOpSubgroupExclusiveMul:
6225 case glslang::EOpSubgroupExclusiveMin:
6226 case glslang::EOpSubgroupExclusiveMax:
6227 case glslang::EOpSubgroupExclusiveAnd:
6228 case glslang::EOpSubgroupExclusiveOr:
6229 case glslang::EOpSubgroupExclusiveXor:
6230 case glslang::EOpSubgroupQuadSwapHorizontal:
6231 case glslang::EOpSubgroupQuadSwapVertical:
6232 case glslang::EOpSubgroupQuadSwapDiagonal: {
6233 std::vector<spv::Id> operands;
6234 operands.push_back(operand);
6235 return createSubgroupOperation(op, typeId, operands, typeProxy);
6236 }
Rex Xu9d93a232016-05-05 12:30:44 +08006237 case glslang::EOpMbcnt:
6238 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6239 libCall = spv::MbcntAMD;
6240 break;
6241
6242 case glslang::EOpCubeFaceIndex:
6243 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6244 libCall = spv::CubeFaceIndexAMD;
6245 break;
6246
6247 case glslang::EOpCubeFaceCoord:
6248 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6249 libCall = spv::CubeFaceCoordAMD;
6250 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006251 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006252 unaryOp = spv::OpGroupNonUniformPartitionNV;
6253 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006254 case glslang::EOpConstructReference:
6255 unaryOp = spv::OpBitcast;
6256 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006257#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006258
6259 case glslang::EOpCopyObject:
6260 unaryOp = spv::OpCopyObject;
6261 break;
6262
John Kessenich140f3df2015-06-26 16:58:36 -06006263 default:
6264 return 0;
6265 }
6266
6267 spv::Id id;
6268 if (libCall >= 0) {
6269 std::vector<spv::Id> args;
6270 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006271 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006272 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006273 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006274 }
John Kessenich140f3df2015-06-26 16:58:36 -06006275
John Kessenichb9197c82019-08-11 07:41:45 -06006276 decorations.addNoContraction(builder, id);
6277 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006278 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006279}
6280
John Kessenich7a53f762016-01-20 11:19:27 -07006281// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006282spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6283 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006284{
6285 // Handle unary operations vector by vector.
6286 // The result type is the same type as the original type.
6287 // The algorithm is to:
6288 // - break the matrix into vectors
6289 // - apply the operation to each vector
6290 // - make a matrix out the vector results
6291
6292 // get the types sorted out
6293 int numCols = builder.getNumColumns(operand);
6294 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006295 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6296 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006297 std::vector<spv::Id> results;
6298
6299 // do each vector op
6300 for (int c = 0; c < numCols; ++c) {
6301 std::vector<unsigned int> indexes;
6302 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006303 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6304 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006305 decorations.addNoContraction(builder, destVec);
6306 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006307 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006308 }
6309
6310 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006311 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006312 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006313 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006314}
6315
John Kessenichad7645f2018-06-04 19:11:25 -06006316// For converting integers where both the bitwidth and the signedness could
6317// change, but only do the width change here. The caller is still responsible
6318// for the signedness conversion.
6319spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006320{
John Kessenichad7645f2018-06-04 19:11:25 -06006321 // Get the result type width, based on the type to convert to.
6322 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006323 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006324 case glslang::EOpConvInt16ToUint8:
6325 case glslang::EOpConvIntToUint8:
6326 case glslang::EOpConvInt64ToUint8:
6327 case glslang::EOpConvUint16ToInt8:
6328 case glslang::EOpConvUintToInt8:
6329 case glslang::EOpConvUint64ToInt8:
6330 width = 8;
6331 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006332 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006333 case glslang::EOpConvIntToUint16:
6334 case glslang::EOpConvInt64ToUint16:
6335 case glslang::EOpConvUint8ToInt16:
6336 case glslang::EOpConvUintToInt16:
6337 case glslang::EOpConvUint64ToInt16:
6338 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006339 break;
6340 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006341 case glslang::EOpConvInt16ToUint:
6342 case glslang::EOpConvInt64ToUint:
6343 case glslang::EOpConvUint8ToInt:
6344 case glslang::EOpConvUint16ToInt:
6345 case glslang::EOpConvUint64ToInt:
6346 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006347 break;
6348 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006349 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006350 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006351 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006352 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006353 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006354 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006355 break;
6356
6357 default:
6358 assert(false && "Default missing");
6359 break;
6360 }
6361
John Kessenichad7645f2018-06-04 19:11:25 -06006362 // Get the conversion operation and result type,
6363 // based on the target width, but the source type.
6364 spv::Id type = spv::NoType;
6365 spv::Op convOp = spv::OpNop;
6366 switch(op) {
6367 case glslang::EOpConvInt8ToUint16:
6368 case glslang::EOpConvInt8ToUint:
6369 case glslang::EOpConvInt8ToUint64:
6370 case glslang::EOpConvInt16ToUint8:
6371 case glslang::EOpConvInt16ToUint:
6372 case glslang::EOpConvInt16ToUint64:
6373 case glslang::EOpConvIntToUint8:
6374 case glslang::EOpConvIntToUint16:
6375 case glslang::EOpConvIntToUint64:
6376 case glslang::EOpConvInt64ToUint8:
6377 case glslang::EOpConvInt64ToUint16:
6378 case glslang::EOpConvInt64ToUint:
6379 convOp = spv::OpSConvert;
6380 type = builder.makeIntType(width);
6381 break;
6382 default:
6383 convOp = spv::OpUConvert;
6384 type = builder.makeUintType(width);
6385 break;
6386 }
6387
John Kessenich66011cb2018-03-06 16:12:04 -07006388 if (vectorSize > 0)
6389 type = builder.makeVectorType(type, vectorSize);
6390
John Kessenichad7645f2018-06-04 19:11:25 -06006391 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006392}
6393
John Kessenichead86222018-03-28 18:01:20 -06006394spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6395 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006396{
6397 spv::Op convOp = spv::OpNop;
6398 spv::Id zero = 0;
6399 spv::Id one = 0;
6400
6401 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6402
6403 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006404 case glslang::EOpConvIntToBool:
6405 case glslang::EOpConvUintToBool:
6406 zero = builder.makeUintConstant(0);
6407 zero = makeSmearedConstant(zero, vectorSize);
6408 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006409 case glslang::EOpConvFloatToBool:
6410 zero = builder.makeFloatConstant(0.0F);
6411 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006412 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006413 case glslang::EOpConvBoolToFloat:
6414 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006415 zero = builder.makeFloatConstant(0.0F);
6416 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006417 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006418
John Kessenich140f3df2015-06-26 16:58:36 -06006419 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006420 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006421#ifndef GLSLANG_WEB
6422 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006423 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006424 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006425 } else
6426#endif
6427 {
6428 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006429 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006430 }
Rex Xucabbb782017-03-24 13:41:14 +08006431
John Kessenich140f3df2015-06-26 16:58:36 -06006432 convOp = spv::OpSelect;
6433 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006434
John Kessenich140f3df2015-06-26 16:58:36 -06006435 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006436 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006437#ifndef GLSLANG_WEB
6438 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006439 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006440 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006441 } else
6442#endif
6443 {
6444 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006445 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006446 }
Rex Xucabbb782017-03-24 13:41:14 +08006447
John Kessenich140f3df2015-06-26 16:58:36 -06006448 convOp = spv::OpSelect;
6449 break;
6450
John Kessenich66011cb2018-03-06 16:12:04 -07006451 case glslang::EOpConvInt8ToFloat16:
6452 case glslang::EOpConvInt8ToFloat:
6453 case glslang::EOpConvInt8ToDouble:
6454 case glslang::EOpConvInt16ToFloat16:
6455 case glslang::EOpConvInt16ToFloat:
6456 case glslang::EOpConvInt16ToDouble:
6457 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006458 case glslang::EOpConvIntToFloat:
6459 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006460 case glslang::EOpConvInt64ToFloat:
6461 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006462 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006463 convOp = spv::OpConvertSToF;
6464 break;
6465
John Kessenich66011cb2018-03-06 16:12:04 -07006466 case glslang::EOpConvUint8ToFloat16:
6467 case glslang::EOpConvUint8ToFloat:
6468 case glslang::EOpConvUint8ToDouble:
6469 case glslang::EOpConvUint16ToFloat16:
6470 case glslang::EOpConvUint16ToFloat:
6471 case glslang::EOpConvUint16ToDouble:
6472 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006473 case glslang::EOpConvUintToFloat:
6474 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006475 case glslang::EOpConvUint64ToFloat:
6476 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006477 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006478 convOp = spv::OpConvertUToF;
6479 break;
6480
John Kessenich66011cb2018-03-06 16:12:04 -07006481 case glslang::EOpConvFloat16ToInt8:
6482 case glslang::EOpConvFloatToInt8:
6483 case glslang::EOpConvDoubleToInt8:
6484 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006485 case glslang::EOpConvFloatToInt16:
6486 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006487 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006488 case glslang::EOpConvFloatToInt:
6489 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006490 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006491 case glslang::EOpConvFloatToInt64:
6492 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006493 convOp = spv::OpConvertFToS;
6494 break;
6495
John Kessenich66011cb2018-03-06 16:12:04 -07006496 case glslang::EOpConvUint8ToInt8:
6497 case glslang::EOpConvInt8ToUint8:
6498 case glslang::EOpConvUint16ToInt16:
6499 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006500 case glslang::EOpConvUintToInt:
6501 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006502 case glslang::EOpConvUint64ToInt64:
6503 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006504 if (builder.isInSpecConstCodeGenMode()) {
6505 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006506#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006507 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6508 zero = builder.makeUint8Constant(0);
6509 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006510 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006511 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6512 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006513 } else
6514#endif
6515 {
Rex Xucabbb782017-03-24 13:41:14 +08006516 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006517 }
qining189b2032016-04-12 23:16:20 -04006518 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006519 // Use OpIAdd, instead of OpBitcast to do the conversion when
6520 // generating for OpSpecConstantOp instruction.
6521 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6522 }
6523 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006524 convOp = spv::OpBitcast;
6525 break;
6526
John Kessenich66011cb2018-03-06 16:12:04 -07006527 case glslang::EOpConvFloat16ToUint8:
6528 case glslang::EOpConvFloatToUint8:
6529 case glslang::EOpConvDoubleToUint8:
6530 case glslang::EOpConvFloat16ToUint16:
6531 case glslang::EOpConvFloatToUint16:
6532 case glslang::EOpConvDoubleToUint16:
6533 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006534 case glslang::EOpConvFloatToUint:
6535 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006536 case glslang::EOpConvFloatToUint64:
6537 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006538 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006539 convOp = spv::OpConvertFToU;
6540 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006541
John Kessenich39697cd2019-08-08 10:35:51 -06006542#ifndef GLSLANG_WEB
6543 case glslang::EOpConvInt8ToBool:
6544 case glslang::EOpConvUint8ToBool:
6545 zero = builder.makeUint8Constant(0);
6546 zero = makeSmearedConstant(zero, vectorSize);
6547 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6548 case glslang::EOpConvInt16ToBool:
6549 case glslang::EOpConvUint16ToBool:
6550 zero = builder.makeUint16Constant(0);
6551 zero = makeSmearedConstant(zero, vectorSize);
6552 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6553 case glslang::EOpConvInt64ToBool:
6554 case glslang::EOpConvUint64ToBool:
6555 zero = builder.makeUint64Constant(0);
6556 zero = makeSmearedConstant(zero, vectorSize);
6557 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6558 case glslang::EOpConvDoubleToBool:
6559 zero = builder.makeDoubleConstant(0.0);
6560 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006561 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006562 case glslang::EOpConvFloat16ToBool:
6563 zero = builder.makeFloat16Constant(0.0F);
6564 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006565 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006566 case glslang::EOpConvBoolToDouble:
6567 convOp = spv::OpSelect;
6568 zero = builder.makeDoubleConstant(0.0);
6569 one = builder.makeDoubleConstant(1.0);
6570 break;
6571 case glslang::EOpConvBoolToFloat16:
6572 convOp = spv::OpSelect;
6573 zero = builder.makeFloat16Constant(0.0F);
6574 one = builder.makeFloat16Constant(1.0F);
6575 break;
6576 case glslang::EOpConvBoolToInt8:
6577 zero = builder.makeInt8Constant(0);
6578 one = builder.makeInt8Constant(1);
6579 convOp = spv::OpSelect;
6580 break;
6581 case glslang::EOpConvBoolToUint8:
6582 zero = builder.makeUint8Constant(0);
6583 one = builder.makeUint8Constant(1);
6584 convOp = spv::OpSelect;
6585 break;
6586 case glslang::EOpConvBoolToInt16:
6587 zero = builder.makeInt16Constant(0);
6588 one = builder.makeInt16Constant(1);
6589 convOp = spv::OpSelect;
6590 break;
6591 case glslang::EOpConvBoolToUint16:
6592 zero = builder.makeUint16Constant(0);
6593 one = builder.makeUint16Constant(1);
6594 convOp = spv::OpSelect;
6595 break;
6596 case glslang::EOpConvDoubleToFloat:
6597 case glslang::EOpConvFloatToDouble:
6598 case glslang::EOpConvDoubleToFloat16:
6599 case glslang::EOpConvFloat16ToDouble:
6600 case glslang::EOpConvFloatToFloat16:
6601 case glslang::EOpConvFloat16ToFloat:
6602 convOp = spv::OpFConvert;
6603 if (builder.isMatrixType(destType))
6604 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6605 break;
6606
John Kessenich66011cb2018-03-06 16:12:04 -07006607 case glslang::EOpConvInt8ToInt16:
6608 case glslang::EOpConvInt8ToInt:
6609 case glslang::EOpConvInt8ToInt64:
6610 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006611 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006612 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006613 case glslang::EOpConvIntToInt8:
6614 case glslang::EOpConvIntToInt16:
6615 case glslang::EOpConvIntToInt64:
6616 case glslang::EOpConvInt64ToInt8:
6617 case glslang::EOpConvInt64ToInt16:
6618 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006619 convOp = spv::OpSConvert;
6620 break;
6621
John Kessenich66011cb2018-03-06 16:12:04 -07006622 case glslang::EOpConvUint8ToUint16:
6623 case glslang::EOpConvUint8ToUint:
6624 case glslang::EOpConvUint8ToUint64:
6625 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006626 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006627 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006628 case glslang::EOpConvUintToUint8:
6629 case glslang::EOpConvUintToUint16:
6630 case glslang::EOpConvUintToUint64:
6631 case glslang::EOpConvUint64ToUint8:
6632 case glslang::EOpConvUint64ToUint16:
6633 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006634 convOp = spv::OpUConvert;
6635 break;
6636
John Kessenich66011cb2018-03-06 16:12:04 -07006637 case glslang::EOpConvInt8ToUint16:
6638 case glslang::EOpConvInt8ToUint:
6639 case glslang::EOpConvInt8ToUint64:
6640 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006641 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006642 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006643 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006644 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006645 case glslang::EOpConvIntToUint64:
6646 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006647 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006648 case glslang::EOpConvInt64ToUint:
6649 case glslang::EOpConvUint8ToInt16:
6650 case glslang::EOpConvUint8ToInt:
6651 case glslang::EOpConvUint8ToInt64:
6652 case glslang::EOpConvUint16ToInt8:
6653 case glslang::EOpConvUint16ToInt:
6654 case glslang::EOpConvUint16ToInt64:
6655 case glslang::EOpConvUintToInt8:
6656 case glslang::EOpConvUintToInt16:
6657 case glslang::EOpConvUintToInt64:
6658 case glslang::EOpConvUint64ToInt8:
6659 case glslang::EOpConvUint64ToInt16:
6660 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006661 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006662 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006663
6664 if (builder.isInSpecConstCodeGenMode()) {
6665 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006666 switch(op) {
6667 case glslang::EOpConvInt16ToUint8:
6668 case glslang::EOpConvIntToUint8:
6669 case glslang::EOpConvInt64ToUint8:
6670 case glslang::EOpConvUint16ToInt8:
6671 case glslang::EOpConvUintToInt8:
6672 case glslang::EOpConvUint64ToInt8:
6673 zero = builder.makeUint8Constant(0);
6674 break;
6675 case glslang::EOpConvInt8ToUint16:
6676 case glslang::EOpConvIntToUint16:
6677 case glslang::EOpConvInt64ToUint16:
6678 case glslang::EOpConvUint8ToInt16:
6679 case glslang::EOpConvUintToInt16:
6680 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006681 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006682 break;
6683 case glslang::EOpConvInt8ToUint:
6684 case glslang::EOpConvInt16ToUint:
6685 case glslang::EOpConvInt64ToUint:
6686 case glslang::EOpConvUint8ToInt:
6687 case glslang::EOpConvUint16ToInt:
6688 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006689 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006690 break;
6691 case glslang::EOpConvInt8ToUint64:
6692 case glslang::EOpConvInt16ToUint64:
6693 case glslang::EOpConvIntToUint64:
6694 case glslang::EOpConvUint8ToInt64:
6695 case glslang::EOpConvUint16ToInt64:
6696 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006697 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006698 break;
6699 default:
6700 assert(false && "Default missing");
6701 break;
6702 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006703 zero = makeSmearedConstant(zero, vectorSize);
6704 // Use OpIAdd, instead of OpBitcast to do the conversion when
6705 // generating for OpSpecConstantOp instruction.
6706 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6707 }
6708 // For normal run-time conversion instruction, use OpBitcast.
6709 convOp = spv::OpBitcast;
6710 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006711 case glslang::EOpConvUint64ToPtr:
6712 convOp = spv::OpConvertUToPtr;
6713 break;
6714 case glslang::EOpConvPtrToUint64:
6715 convOp = spv::OpConvertPtrToU;
6716 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006717 case glslang::EOpConvPtrToUvec2:
6718 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006719 if (builder.isVector(operand))
6720 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6721 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006722 convOp = spv::OpBitcast;
6723 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006724#endif
6725
John Kessenich140f3df2015-06-26 16:58:36 -06006726 default:
6727 break;
6728 }
6729
6730 spv::Id result = 0;
6731 if (convOp == spv::OpNop)
6732 return result;
6733
6734 if (convOp == spv::OpSelect) {
6735 zero = makeSmearedConstant(zero, vectorSize);
6736 one = makeSmearedConstant(one, vectorSize);
6737 result = builder.createTriOp(convOp, destType, operand, one, zero);
6738 } else
6739 result = builder.createUnaryOp(convOp, destType, operand);
6740
John Kessenichead86222018-03-28 18:01:20 -06006741 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006742 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006743 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006744}
6745
6746spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6747{
6748 if (vectorSize == 0)
6749 return constant;
6750
6751 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6752 std::vector<spv::Id> components;
6753 for (int c = 0; c < vectorSize; ++c)
6754 components.push_back(constant);
6755 return builder.makeCompositeConstant(vectorTypeId, components);
6756}
6757
John Kessenich426394d2015-07-23 10:22:48 -06006758// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006759spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6760 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6761 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006762{
6763 spv::Op opCode = spv::OpNop;
6764
6765 switch (op) {
6766 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006767 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006768 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006769 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006770 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6771 opCode = spv::OpAtomicFAddEXT;
6772 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6773 if (typeProxy == glslang::EbtFloat)
6774 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6775 else
6776 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6777 }
John Kessenich426394d2015-07-23 10:22:48 -06006778 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006779 case glslang::EOpAtomicCounterSubtract:
6780 opCode = spv::OpAtomicISub;
6781 break;
John Kessenich426394d2015-07-23 10:22:48 -06006782 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006783 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006784 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006785 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6786 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006787 break;
6788 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006789 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006790 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006791 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6792 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006793 break;
6794 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006795 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006796 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006797 opCode = spv::OpAtomicAnd;
6798 break;
6799 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006800 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006801 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006802 opCode = spv::OpAtomicOr;
6803 break;
6804 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006805 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006806 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006807 opCode = spv::OpAtomicXor;
6808 break;
6809 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006810 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006811 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006812 opCode = spv::OpAtomicExchange;
6813 break;
6814 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006815 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006816 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006817 opCode = spv::OpAtomicCompareExchange;
6818 break;
6819 case glslang::EOpAtomicCounterIncrement:
6820 opCode = spv::OpAtomicIIncrement;
6821 break;
6822 case glslang::EOpAtomicCounterDecrement:
6823 opCode = spv::OpAtomicIDecrement;
6824 break;
6825 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006826 case glslang::EOpImageAtomicLoad:
6827 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006828 opCode = spv::OpAtomicLoad;
6829 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006830 case glslang::EOpAtomicStore:
6831 case glslang::EOpImageAtomicStore:
6832 opCode = spv::OpAtomicStore;
6833 break;
John Kessenich426394d2015-07-23 10:22:48 -06006834 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006835 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006836 break;
6837 }
6838
Rex Xue8fe8b02017-09-26 15:42:56 +08006839 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6840 builder.addCapability(spv::CapabilityInt64Atomics);
6841
John Kessenich426394d2015-07-23 10:22:48 -06006842 // Sort out the operands
6843 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006844 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006845 // - compare-exchange swaps the value and comparator
6846 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006847 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006848 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6849 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6850 spv::Id scopeId;
6851 if (glslangIntermediate->usingVulkanMemoryModel()) {
6852 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6853 } else {
6854 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6855 }
6856 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006857 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6858 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006859 spv::MemorySemanticsVolatileMask :
6860 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006861 spv::Id semanticsId2 = semanticsId;
6862
6863 pointerId = operands[0];
6864 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6865 // no additional operands
6866 } else if (opCode == spv::OpAtomicCompareExchange) {
6867 compareId = operands[1];
6868 valueId = operands[2];
6869 if (operands.size() > 3) {
6870 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006871 semanticsId = builder.makeUintConstant(
6872 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6873 semanticsId2 = builder.makeUintConstant(
6874 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006875 }
6876 } else if (opCode == spv::OpAtomicLoad) {
6877 if (operands.size() > 1) {
6878 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006879 semanticsId = builder.makeUintConstant(
6880 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006881 }
6882 } else {
6883 // atomic store or RMW
6884 valueId = operands[1];
6885 if (operands.size() > 2) {
6886 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006887 semanticsId = builder.makeUintConstant
6888 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006889 }
Rex Xu04db3f52015-09-16 11:44:02 +08006890 }
John Kessenich426394d2015-07-23 10:22:48 -06006891
Jeff Bolz36831c92018-09-05 10:11:41 -05006892 // Check for capabilities
6893 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006894 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6895 spv::MemorySemanticsMakeVisibleKHRMask |
6896 spv::MemorySemanticsOutputMemoryKHRMask |
6897 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006898 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6899 }
John Kessenich426394d2015-07-23 10:22:48 -06006900
Jeff Bolz36831c92018-09-05 10:11:41 -05006901 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6902 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6903 }
John Kessenich48d6e792017-10-06 21:21:48 -06006904
Jeff Bolz36831c92018-09-05 10:11:41 -05006905 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6906 spvAtomicOperands.push_back(pointerId);
6907 spvAtomicOperands.push_back(scopeId);
6908 spvAtomicOperands.push_back(semanticsId);
6909 if (opCode == spv::OpAtomicCompareExchange) {
6910 spvAtomicOperands.push_back(semanticsId2);
6911 spvAtomicOperands.push_back(valueId);
6912 spvAtomicOperands.push_back(compareId);
6913 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6914 spvAtomicOperands.push_back(valueId);
6915 }
John Kessenich48d6e792017-10-06 21:21:48 -06006916
Jeff Bolz36831c92018-09-05 10:11:41 -05006917 if (opCode == spv::OpAtomicStore) {
6918 builder.createNoResultOp(opCode, spvAtomicOperands);
6919 return 0;
6920 } else {
6921 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6922
6923 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6924 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6925 if (op == glslang::EOpAtomicCounterDecrement)
6926 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6927
6928 return resultId;
6929 }
John Kessenich426394d2015-07-23 10:22:48 -06006930}
6931
John Kessenich91cef522016-05-05 16:45:40 -06006932// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006933spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6934 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006935{
John Kessenich66011cb2018-03-06 16:12:04 -07006936 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6937 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006938
Rex Xu51596642016-09-21 18:56:12 +08006939 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006940 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006941 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6942
chaocf200da82016-12-20 12:44:35 -08006943 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6944 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006945 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6946 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006947 } else if (op == glslang::EOpAnyInvocation ||
6948 op == glslang::EOpAllInvocations ||
6949 op == glslang::EOpAllInvocationsEqual) {
6950 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6951 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006952 } else {
6953 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006954 if (op == glslang::EOpMinInvocationsNonUniform ||
6955 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006956 op == glslang::EOpAddInvocationsNonUniform ||
6957 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6958 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6959 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6960 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6961 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6962 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006963 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006964
Rex Xu430ef402016-10-14 17:22:23 +08006965 switch (op) {
6966 case glslang::EOpMinInvocations:
6967 case glslang::EOpMaxInvocations:
6968 case glslang::EOpAddInvocations:
6969 case glslang::EOpMinInvocationsNonUniform:
6970 case glslang::EOpMaxInvocationsNonUniform:
6971 case glslang::EOpAddInvocationsNonUniform:
6972 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006973 break;
6974 case glslang::EOpMinInvocationsInclusiveScan:
6975 case glslang::EOpMaxInvocationsInclusiveScan:
6976 case glslang::EOpAddInvocationsInclusiveScan:
6977 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6978 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6979 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6980 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006981 break;
6982 case glslang::EOpMinInvocationsExclusiveScan:
6983 case glslang::EOpMaxInvocationsExclusiveScan:
6984 case glslang::EOpAddInvocationsExclusiveScan:
6985 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6986 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6987 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6988 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006989 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006990 default:
6991 break;
Rex Xu430ef402016-10-14 17:22:23 +08006992 }
John Kessenich149afc32018-08-14 13:31:43 -06006993 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6994 spvGroupOperands.push_back(scope);
6995 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006996 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006997 spvGroupOperands.push_back(groupOp);
6998 }
Rex Xu51596642016-09-21 18:56:12 +08006999 }
7000
John Kessenich149afc32018-08-14 13:31:43 -06007001 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
7002 spv::IdImmediate op = { true, *opIt };
7003 spvGroupOperands.push_back(op);
7004 }
John Kessenich91cef522016-05-05 16:45:40 -06007005
7006 switch (op) {
7007 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007008 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08007009 break;
John Kessenich91cef522016-05-05 16:45:40 -06007010 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007011 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08007012 break;
John Kessenich91cef522016-05-05 16:45:40 -06007013 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08007014 opCode = spv::OpSubgroupAllEqualKHR;
7015 break;
Rex Xu51596642016-09-21 18:56:12 +08007016 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08007017 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08007018 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007019 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007020 break;
7021 case glslang::EOpReadFirstInvocation:
7022 opCode = spv::OpSubgroupFirstInvocationKHR;
7023 break;
7024 case glslang::EOpBallot:
7025 {
7026 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
7027 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
7028 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
7029 //
7030 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
7031 //
7032 spv::Id uintType = builder.makeUintType(32);
7033 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
7034 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
7035
7036 std::vector<spv::Id> components;
7037 components.push_back(builder.createCompositeExtract(result, uintType, 0));
7038 components.push_back(builder.createCompositeExtract(result, uintType, 1));
7039
7040 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
7041 return builder.createUnaryOp(spv::OpBitcast, typeId,
7042 builder.createCompositeConstruct(uvec2Type, components));
7043 }
7044
Rex Xu9d93a232016-05-05 12:30:44 +08007045 case glslang::EOpMinInvocations:
7046 case glslang::EOpMaxInvocations:
7047 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08007048 case glslang::EOpMinInvocationsInclusiveScan:
7049 case glslang::EOpMaxInvocationsInclusiveScan:
7050 case glslang::EOpAddInvocationsInclusiveScan:
7051 case glslang::EOpMinInvocationsExclusiveScan:
7052 case glslang::EOpMaxInvocationsExclusiveScan:
7053 case glslang::EOpAddInvocationsExclusiveScan:
7054 if (op == glslang::EOpMinInvocations ||
7055 op == glslang::EOpMinInvocationsInclusiveScan ||
7056 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007057 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007058 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007059 else {
7060 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007061 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007062 else
Rex Xu51596642016-09-21 18:56:12 +08007063 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007064 }
Rex Xu430ef402016-10-14 17:22:23 +08007065 } else if (op == glslang::EOpMaxInvocations ||
7066 op == glslang::EOpMaxInvocationsInclusiveScan ||
7067 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007068 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007069 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007070 else {
7071 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007072 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007073 else
Rex Xu51596642016-09-21 18:56:12 +08007074 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007075 }
7076 } else {
7077 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007078 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007079 else
Rex Xu51596642016-09-21 18:56:12 +08007080 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007081 }
7082
Rex Xu2bbbe062016-08-23 15:41:05 +08007083 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007084 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007085
7086 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007087 case glslang::EOpMinInvocationsNonUniform:
7088 case glslang::EOpMaxInvocationsNonUniform:
7089 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007090 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7091 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7092 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7093 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7094 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7095 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7096 if (op == glslang::EOpMinInvocationsNonUniform ||
7097 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7098 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007099 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007100 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007101 else {
7102 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007103 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007104 else
Rex Xu51596642016-09-21 18:56:12 +08007105 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007106 }
7107 }
Rex Xu430ef402016-10-14 17:22:23 +08007108 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7109 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7110 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007111 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007112 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007113 else {
7114 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007115 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007116 else
Rex Xu51596642016-09-21 18:56:12 +08007117 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007118 }
7119 }
7120 else {
7121 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007122 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007123 else
Rex Xu51596642016-09-21 18:56:12 +08007124 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007125 }
7126
Rex Xu2bbbe062016-08-23 15:41:05 +08007127 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007128 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007129
7130 break;
John Kessenich91cef522016-05-05 16:45:40 -06007131 default:
7132 logger->missingFunctionality("invocation operation");
7133 return spv::NoResult;
7134 }
Rex Xu51596642016-09-21 18:56:12 +08007135
7136 assert(opCode != spv::OpNop);
7137 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007138}
7139
Rex Xu2bbbe062016-08-23 15:41:05 +08007140// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007141spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7142 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007143{
7144 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7145 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007146 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007147 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007148 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7149 op == spv::OpGroupSMinNonUniformAMD ||
7150 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7151 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007152 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7153
7154 // Handle group invocation operations scalar by scalar.
7155 // The result type is the same type as the original type.
7156 // The algorithm is to:
7157 // - break the vector into scalars
7158 // - apply the operation to each scalar
7159 // - make a vector out the scalar results
7160
7161 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007162 int numComponents = builder.getNumComponents(operands[0]);
7163 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007164 std::vector<spv::Id> results;
7165
7166 // do each scalar op
7167 for (int comp = 0; comp < numComponents; ++comp) {
7168 std::vector<unsigned int> indexes;
7169 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007170 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7171 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007172 if (op == spv::OpSubgroupReadInvocationKHR) {
7173 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007174 spv::IdImmediate operand = { true, operands[1] };
7175 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007176 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007177 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7178 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007179 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007180 spv::IdImmediate operand = { true, operands[1] };
7181 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007182 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007183 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7184 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007185 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007186 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007187 spvGroupOperands.push_back(scalar);
7188 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007189
Rex Xub7072052016-09-26 15:53:40 +08007190 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007191 }
7192
7193 // put the pieces together
7194 return builder.createCompositeConstruct(typeId, results);
7195}
Rex Xu2bbbe062016-08-23 15:41:05 +08007196
John Kessenich66011cb2018-03-06 16:12:04 -07007197// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007198spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7199 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007200{
7201 // Add the required capabilities.
7202 switch (op) {
7203 case glslang::EOpSubgroupElect:
7204 builder.addCapability(spv::CapabilityGroupNonUniform);
7205 break;
7206 case glslang::EOpSubgroupAll:
7207 case glslang::EOpSubgroupAny:
7208 case glslang::EOpSubgroupAllEqual:
7209 builder.addCapability(spv::CapabilityGroupNonUniform);
7210 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7211 break;
7212 case glslang::EOpSubgroupBroadcast:
7213 case glslang::EOpSubgroupBroadcastFirst:
7214 case glslang::EOpSubgroupBallot:
7215 case glslang::EOpSubgroupInverseBallot:
7216 case glslang::EOpSubgroupBallotBitExtract:
7217 case glslang::EOpSubgroupBallotBitCount:
7218 case glslang::EOpSubgroupBallotInclusiveBitCount:
7219 case glslang::EOpSubgroupBallotExclusiveBitCount:
7220 case glslang::EOpSubgroupBallotFindLSB:
7221 case glslang::EOpSubgroupBallotFindMSB:
7222 builder.addCapability(spv::CapabilityGroupNonUniform);
7223 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7224 break;
7225 case glslang::EOpSubgroupShuffle:
7226 case glslang::EOpSubgroupShuffleXor:
7227 builder.addCapability(spv::CapabilityGroupNonUniform);
7228 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7229 break;
7230 case glslang::EOpSubgroupShuffleUp:
7231 case glslang::EOpSubgroupShuffleDown:
7232 builder.addCapability(spv::CapabilityGroupNonUniform);
7233 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7234 break;
7235 case glslang::EOpSubgroupAdd:
7236 case glslang::EOpSubgroupMul:
7237 case glslang::EOpSubgroupMin:
7238 case glslang::EOpSubgroupMax:
7239 case glslang::EOpSubgroupAnd:
7240 case glslang::EOpSubgroupOr:
7241 case glslang::EOpSubgroupXor:
7242 case glslang::EOpSubgroupInclusiveAdd:
7243 case glslang::EOpSubgroupInclusiveMul:
7244 case glslang::EOpSubgroupInclusiveMin:
7245 case glslang::EOpSubgroupInclusiveMax:
7246 case glslang::EOpSubgroupInclusiveAnd:
7247 case glslang::EOpSubgroupInclusiveOr:
7248 case glslang::EOpSubgroupInclusiveXor:
7249 case glslang::EOpSubgroupExclusiveAdd:
7250 case glslang::EOpSubgroupExclusiveMul:
7251 case glslang::EOpSubgroupExclusiveMin:
7252 case glslang::EOpSubgroupExclusiveMax:
7253 case glslang::EOpSubgroupExclusiveAnd:
7254 case glslang::EOpSubgroupExclusiveOr:
7255 case glslang::EOpSubgroupExclusiveXor:
7256 builder.addCapability(spv::CapabilityGroupNonUniform);
7257 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7258 break;
7259 case glslang::EOpSubgroupClusteredAdd:
7260 case glslang::EOpSubgroupClusteredMul:
7261 case glslang::EOpSubgroupClusteredMin:
7262 case glslang::EOpSubgroupClusteredMax:
7263 case glslang::EOpSubgroupClusteredAnd:
7264 case glslang::EOpSubgroupClusteredOr:
7265 case glslang::EOpSubgroupClusteredXor:
7266 builder.addCapability(spv::CapabilityGroupNonUniform);
7267 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7268 break;
7269 case glslang::EOpSubgroupQuadBroadcast:
7270 case glslang::EOpSubgroupQuadSwapHorizontal:
7271 case glslang::EOpSubgroupQuadSwapVertical:
7272 case glslang::EOpSubgroupQuadSwapDiagonal:
7273 builder.addCapability(spv::CapabilityGroupNonUniform);
7274 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7275 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007276 case glslang::EOpSubgroupPartitionedAdd:
7277 case glslang::EOpSubgroupPartitionedMul:
7278 case glslang::EOpSubgroupPartitionedMin:
7279 case glslang::EOpSubgroupPartitionedMax:
7280 case glslang::EOpSubgroupPartitionedAnd:
7281 case glslang::EOpSubgroupPartitionedOr:
7282 case glslang::EOpSubgroupPartitionedXor:
7283 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7284 case glslang::EOpSubgroupPartitionedInclusiveMul:
7285 case glslang::EOpSubgroupPartitionedInclusiveMin:
7286 case glslang::EOpSubgroupPartitionedInclusiveMax:
7287 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7288 case glslang::EOpSubgroupPartitionedInclusiveOr:
7289 case glslang::EOpSubgroupPartitionedInclusiveXor:
7290 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7291 case glslang::EOpSubgroupPartitionedExclusiveMul:
7292 case glslang::EOpSubgroupPartitionedExclusiveMin:
7293 case glslang::EOpSubgroupPartitionedExclusiveMax:
7294 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7295 case glslang::EOpSubgroupPartitionedExclusiveOr:
7296 case glslang::EOpSubgroupPartitionedExclusiveXor:
7297 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7298 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7299 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007300 default: assert(0 && "Unhandled subgroup operation!");
7301 }
7302
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007303
7304 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7305 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007306 const bool isBool = typeProxy == glslang::EbtBool;
7307
7308 spv::Op opCode = spv::OpNop;
7309
7310 // Figure out which opcode to use.
7311 switch (op) {
7312 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7313 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7314 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7315 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7316 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7317 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7318 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7319 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7320 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7321 case glslang::EOpSubgroupBallotBitCount:
7322 case glslang::EOpSubgroupBallotInclusiveBitCount:
7323 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7324 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7325 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7326 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7327 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7328 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7329 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7330 case glslang::EOpSubgroupAdd:
7331 case glslang::EOpSubgroupInclusiveAdd:
7332 case glslang::EOpSubgroupExclusiveAdd:
7333 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007334 case glslang::EOpSubgroupPartitionedAdd:
7335 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7336 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007337 if (isFloat) {
7338 opCode = spv::OpGroupNonUniformFAdd;
7339 } else {
7340 opCode = spv::OpGroupNonUniformIAdd;
7341 }
7342 break;
7343 case glslang::EOpSubgroupMul:
7344 case glslang::EOpSubgroupInclusiveMul:
7345 case glslang::EOpSubgroupExclusiveMul:
7346 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007347 case glslang::EOpSubgroupPartitionedMul:
7348 case glslang::EOpSubgroupPartitionedInclusiveMul:
7349 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007350 if (isFloat) {
7351 opCode = spv::OpGroupNonUniformFMul;
7352 } else {
7353 opCode = spv::OpGroupNonUniformIMul;
7354 }
7355 break;
7356 case glslang::EOpSubgroupMin:
7357 case glslang::EOpSubgroupInclusiveMin:
7358 case glslang::EOpSubgroupExclusiveMin:
7359 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007360 case glslang::EOpSubgroupPartitionedMin:
7361 case glslang::EOpSubgroupPartitionedInclusiveMin:
7362 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007363 if (isFloat) {
7364 opCode = spv::OpGroupNonUniformFMin;
7365 } else if (isUnsigned) {
7366 opCode = spv::OpGroupNonUniformUMin;
7367 } else {
7368 opCode = spv::OpGroupNonUniformSMin;
7369 }
7370 break;
7371 case glslang::EOpSubgroupMax:
7372 case glslang::EOpSubgroupInclusiveMax:
7373 case glslang::EOpSubgroupExclusiveMax:
7374 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007375 case glslang::EOpSubgroupPartitionedMax:
7376 case glslang::EOpSubgroupPartitionedInclusiveMax:
7377 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007378 if (isFloat) {
7379 opCode = spv::OpGroupNonUniformFMax;
7380 } else if (isUnsigned) {
7381 opCode = spv::OpGroupNonUniformUMax;
7382 } else {
7383 opCode = spv::OpGroupNonUniformSMax;
7384 }
7385 break;
7386 case glslang::EOpSubgroupAnd:
7387 case glslang::EOpSubgroupInclusiveAnd:
7388 case glslang::EOpSubgroupExclusiveAnd:
7389 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007390 case glslang::EOpSubgroupPartitionedAnd:
7391 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7392 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007393 if (isBool) {
7394 opCode = spv::OpGroupNonUniformLogicalAnd;
7395 } else {
7396 opCode = spv::OpGroupNonUniformBitwiseAnd;
7397 }
7398 break;
7399 case glslang::EOpSubgroupOr:
7400 case glslang::EOpSubgroupInclusiveOr:
7401 case glslang::EOpSubgroupExclusiveOr:
7402 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007403 case glslang::EOpSubgroupPartitionedOr:
7404 case glslang::EOpSubgroupPartitionedInclusiveOr:
7405 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007406 if (isBool) {
7407 opCode = spv::OpGroupNonUniformLogicalOr;
7408 } else {
7409 opCode = spv::OpGroupNonUniformBitwiseOr;
7410 }
7411 break;
7412 case glslang::EOpSubgroupXor:
7413 case glslang::EOpSubgroupInclusiveXor:
7414 case glslang::EOpSubgroupExclusiveXor:
7415 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007416 case glslang::EOpSubgroupPartitionedXor:
7417 case glslang::EOpSubgroupPartitionedInclusiveXor:
7418 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007419 if (isBool) {
7420 opCode = spv::OpGroupNonUniformLogicalXor;
7421 } else {
7422 opCode = spv::OpGroupNonUniformBitwiseXor;
7423 }
7424 break;
7425 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7426 case glslang::EOpSubgroupQuadSwapHorizontal:
7427 case glslang::EOpSubgroupQuadSwapVertical:
7428 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7429 default: assert(0 && "Unhandled subgroup operation!");
7430 }
7431
John Kessenich149afc32018-08-14 13:31:43 -06007432 // get the right Group Operation
7433 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007434 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007435 default:
7436 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007437 case glslang::EOpSubgroupBallotBitCount:
7438 case glslang::EOpSubgroupAdd:
7439 case glslang::EOpSubgroupMul:
7440 case glslang::EOpSubgroupMin:
7441 case glslang::EOpSubgroupMax:
7442 case glslang::EOpSubgroupAnd:
7443 case glslang::EOpSubgroupOr:
7444 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007445 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007446 break;
7447 case glslang::EOpSubgroupBallotInclusiveBitCount:
7448 case glslang::EOpSubgroupInclusiveAdd:
7449 case glslang::EOpSubgroupInclusiveMul:
7450 case glslang::EOpSubgroupInclusiveMin:
7451 case glslang::EOpSubgroupInclusiveMax:
7452 case glslang::EOpSubgroupInclusiveAnd:
7453 case glslang::EOpSubgroupInclusiveOr:
7454 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007455 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007456 break;
7457 case glslang::EOpSubgroupBallotExclusiveBitCount:
7458 case glslang::EOpSubgroupExclusiveAdd:
7459 case glslang::EOpSubgroupExclusiveMul:
7460 case glslang::EOpSubgroupExclusiveMin:
7461 case glslang::EOpSubgroupExclusiveMax:
7462 case glslang::EOpSubgroupExclusiveAnd:
7463 case glslang::EOpSubgroupExclusiveOr:
7464 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007465 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007466 break;
7467 case glslang::EOpSubgroupClusteredAdd:
7468 case glslang::EOpSubgroupClusteredMul:
7469 case glslang::EOpSubgroupClusteredMin:
7470 case glslang::EOpSubgroupClusteredMax:
7471 case glslang::EOpSubgroupClusteredAnd:
7472 case glslang::EOpSubgroupClusteredOr:
7473 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007474 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007475 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007476 case glslang::EOpSubgroupPartitionedAdd:
7477 case glslang::EOpSubgroupPartitionedMul:
7478 case glslang::EOpSubgroupPartitionedMin:
7479 case glslang::EOpSubgroupPartitionedMax:
7480 case glslang::EOpSubgroupPartitionedAnd:
7481 case glslang::EOpSubgroupPartitionedOr:
7482 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007483 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007484 break;
7485 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7486 case glslang::EOpSubgroupPartitionedInclusiveMul:
7487 case glslang::EOpSubgroupPartitionedInclusiveMin:
7488 case glslang::EOpSubgroupPartitionedInclusiveMax:
7489 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7490 case glslang::EOpSubgroupPartitionedInclusiveOr:
7491 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007492 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007493 break;
7494 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7495 case glslang::EOpSubgroupPartitionedExclusiveMul:
7496 case glslang::EOpSubgroupPartitionedExclusiveMin:
7497 case glslang::EOpSubgroupPartitionedExclusiveMax:
7498 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7499 case glslang::EOpSubgroupPartitionedExclusiveOr:
7500 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007501 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007502 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007503 }
7504
John Kessenich149afc32018-08-14 13:31:43 -06007505 // build the instruction
7506 std::vector<spv::IdImmediate> spvGroupOperands;
7507
7508 // Every operation begins with the Execution Scope operand.
7509 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7510 spvGroupOperands.push_back(executionScope);
7511
7512 // Next, for all operations that use a Group Operation, push that as an operand.
7513 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007514 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007515 spvGroupOperands.push_back(groupOperand);
7516 }
7517
John Kessenich66011cb2018-03-06 16:12:04 -07007518 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007519 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7520 spv::IdImmediate operand = { true, *opIt };
7521 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007522 }
7523
7524 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007525 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007526 switch (op) {
7527 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007528 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7529 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7530 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7531 }
7532 if (directionId != spv::NoResult) {
7533 spv::IdImmediate direction = { true, directionId };
7534 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007535 }
7536
7537 return builder.createOp(opCode, typeId, spvGroupOperands);
7538}
7539
John Kessenich8985fc92020-03-03 10:25:07 -07007540spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7541 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007542{
John Kessenich66011cb2018-03-06 16:12:04 -07007543 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7544 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007545
John Kessenich140f3df2015-06-26 16:58:36 -06007546 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007547 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007548 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007549 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007550 spv::Id typeId0 = 0;
7551 if (consumedOperands > 0)
7552 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007553 spv::Id typeId1 = 0;
7554 if (consumedOperands > 1)
7555 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007556 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007557
7558 switch (op) {
7559 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007560 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007561 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007562 else if (isUnsigned)
7563 libCall = spv::GLSLstd450UMin;
7564 else
7565 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007566 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007567 break;
7568 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007569 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007570 break;
7571 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007572 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007573 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007574 else if (isUnsigned)
7575 libCall = spv::GLSLstd450UMax;
7576 else
7577 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007578 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007579 break;
7580 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007581 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007582 break;
7583 case glslang::EOpDot:
7584 opCode = spv::OpDot;
7585 break;
7586 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007587 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007588 break;
7589
7590 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007591 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007592 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007593 else if (isUnsigned)
7594 libCall = spv::GLSLstd450UClamp;
7595 else
7596 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007597 builder.promoteScalar(precision, operands.front(), operands[1]);
7598 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007599 break;
7600 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007601 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7602 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007603 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007604 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007605 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007606 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007607 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007608 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007609 break;
7610 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007611 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007612 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007613 break;
7614 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007615 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007616 builder.promoteScalar(precision, operands[0], operands[2]);
7617 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007618 break;
7619
7620 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007621 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007622 break;
7623 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007624 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007625 break;
7626 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007627 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007628 break;
7629 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007630 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007631 break;
7632 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007633 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007634 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007635 case glslang::EOpBarrier:
7636 {
7637 // This is for the extended controlBarrier function, with four operands.
7638 // The unextended barrier() goes through createNoArgOperation.
7639 assert(operands.size() == 4);
7640 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7641 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7642 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007643 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7644 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007645 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7646 spv::MemorySemanticsMakeVisibleKHRMask |
7647 spv::MemorySemanticsOutputMemoryKHRMask |
7648 spv::MemorySemanticsVolatileMask)) {
7649 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7650 }
John Kessenich8985fc92020-03-03 10:25:07 -07007651 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7652 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007653 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7654 }
7655 return 0;
7656 }
7657 break;
7658 case glslang::EOpMemoryBarrier:
7659 {
7660 // This is for the extended memoryBarrier function, with three operands.
7661 // The unextended memoryBarrier() goes through createNoArgOperation.
7662 assert(operands.size() == 3);
7663 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7664 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7665 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7666 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7667 spv::MemorySemanticsMakeVisibleKHRMask |
7668 spv::MemorySemanticsOutputMemoryKHRMask |
7669 spv::MemorySemanticsVolatileMask)) {
7670 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7671 }
7672 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7673 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7674 }
7675 return 0;
7676 }
7677 break;
7678
John Kessenicha28f7a72019-08-06 07:00:58 -06007679#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007680 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007681 if (typeProxy == glslang::EbtFloat16)
7682 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007683 libCall = spv::GLSLstd450InterpolateAtSample;
7684 break;
7685 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007686 if (typeProxy == glslang::EbtFloat16)
7687 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007688 libCall = spv::GLSLstd450InterpolateAtOffset;
7689 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007690 case glslang::EOpAddCarry:
7691 opCode = spv::OpIAddCarry;
7692 typeId = builder.makeStructResultType(typeId0, typeId0);
7693 consumedOperands = 2;
7694 break;
7695 case glslang::EOpSubBorrow:
7696 opCode = spv::OpISubBorrow;
7697 typeId = builder.makeStructResultType(typeId0, typeId0);
7698 consumedOperands = 2;
7699 break;
7700 case glslang::EOpUMulExtended:
7701 opCode = spv::OpUMulExtended;
7702 typeId = builder.makeStructResultType(typeId0, typeId0);
7703 consumedOperands = 2;
7704 break;
7705 case glslang::EOpIMulExtended:
7706 opCode = spv::OpSMulExtended;
7707 typeId = builder.makeStructResultType(typeId0, typeId0);
7708 consumedOperands = 2;
7709 break;
7710 case glslang::EOpBitfieldExtract:
7711 if (isUnsigned)
7712 opCode = spv::OpBitFieldUExtract;
7713 else
7714 opCode = spv::OpBitFieldSExtract;
7715 break;
7716 case glslang::EOpBitfieldInsert:
7717 opCode = spv::OpBitFieldInsert;
7718 break;
7719
7720 case glslang::EOpFma:
7721 libCall = spv::GLSLstd450Fma;
7722 break;
7723 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007724 {
7725 libCall = spv::GLSLstd450FrexpStruct;
7726 assert(builder.isPointerType(typeId1));
7727 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007728 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007729 if (width == 16)
7730 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7731 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007732 if (builder.getNumComponents(operands[0]) == 1)
7733 frexpIntType = builder.makeIntegerType(width, true);
7734 else
John Kessenich8985fc92020-03-03 10:25:07 -07007735 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7736 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007737 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7738 consumedOperands = 1;
7739 }
John Kessenich55e7d112015-11-15 21:33:39 -07007740 break;
7741 case glslang::EOpLdexp:
7742 libCall = spv::GLSLstd450Ldexp;
7743 break;
7744
Rex Xu574ab042016-04-14 16:53:07 +08007745 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007746 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007747
John Kessenich66011cb2018-03-06 16:12:04 -07007748 case glslang::EOpSubgroupBroadcast:
7749 case glslang::EOpSubgroupBallotBitExtract:
7750 case glslang::EOpSubgroupShuffle:
7751 case glslang::EOpSubgroupShuffleXor:
7752 case glslang::EOpSubgroupShuffleUp:
7753 case glslang::EOpSubgroupShuffleDown:
7754 case glslang::EOpSubgroupClusteredAdd:
7755 case glslang::EOpSubgroupClusteredMul:
7756 case glslang::EOpSubgroupClusteredMin:
7757 case glslang::EOpSubgroupClusteredMax:
7758 case glslang::EOpSubgroupClusteredAnd:
7759 case glslang::EOpSubgroupClusteredOr:
7760 case glslang::EOpSubgroupClusteredXor:
7761 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007762 case glslang::EOpSubgroupPartitionedAdd:
7763 case glslang::EOpSubgroupPartitionedMul:
7764 case glslang::EOpSubgroupPartitionedMin:
7765 case glslang::EOpSubgroupPartitionedMax:
7766 case glslang::EOpSubgroupPartitionedAnd:
7767 case glslang::EOpSubgroupPartitionedOr:
7768 case glslang::EOpSubgroupPartitionedXor:
7769 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7770 case glslang::EOpSubgroupPartitionedInclusiveMul:
7771 case glslang::EOpSubgroupPartitionedInclusiveMin:
7772 case glslang::EOpSubgroupPartitionedInclusiveMax:
7773 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7774 case glslang::EOpSubgroupPartitionedInclusiveOr:
7775 case glslang::EOpSubgroupPartitionedInclusiveXor:
7776 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7777 case glslang::EOpSubgroupPartitionedExclusiveMul:
7778 case glslang::EOpSubgroupPartitionedExclusiveMin:
7779 case glslang::EOpSubgroupPartitionedExclusiveMax:
7780 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7781 case glslang::EOpSubgroupPartitionedExclusiveOr:
7782 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007783 return createSubgroupOperation(op, typeId, operands, typeProxy);
7784
Rex Xu9d93a232016-05-05 12:30:44 +08007785 case glslang::EOpSwizzleInvocations:
7786 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7787 libCall = spv::SwizzleInvocationsAMD;
7788 break;
7789 case glslang::EOpSwizzleInvocationsMasked:
7790 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7791 libCall = spv::SwizzleInvocationsMaskedAMD;
7792 break;
7793 case glslang::EOpWriteInvocation:
7794 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7795 libCall = spv::WriteInvocationAMD;
7796 break;
7797
7798 case glslang::EOpMin3:
7799 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7800 if (isFloat)
7801 libCall = spv::FMin3AMD;
7802 else {
7803 if (isUnsigned)
7804 libCall = spv::UMin3AMD;
7805 else
7806 libCall = spv::SMin3AMD;
7807 }
7808 break;
7809 case glslang::EOpMax3:
7810 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7811 if (isFloat)
7812 libCall = spv::FMax3AMD;
7813 else {
7814 if (isUnsigned)
7815 libCall = spv::UMax3AMD;
7816 else
7817 libCall = spv::SMax3AMD;
7818 }
7819 break;
7820 case glslang::EOpMid3:
7821 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7822 if (isFloat)
7823 libCall = spv::FMid3AMD;
7824 else {
7825 if (isUnsigned)
7826 libCall = spv::UMid3AMD;
7827 else
7828 libCall = spv::SMid3AMD;
7829 }
7830 break;
7831
7832 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007833 if (typeProxy == glslang::EbtFloat16)
7834 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007835 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7836 libCall = spv::InterpolateAtVertexAMD;
7837 break;
Chao Chen3c366992018-09-19 11:41:59 -07007838
Daniel Kochdb32b242020-03-17 20:42:47 -04007839 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007840 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007841 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007842 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007843 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007844 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007845 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007846 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007847 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007848 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007849
7850 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007851 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7852 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007853 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007854 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7855 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007856 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007857 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7858 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007859 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007860 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7861 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007862 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007863 typeId = builder.makeBoolType();
7864 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007865 break;
7866 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007867 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007868 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007869 break;
7870 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007871 typeId = builder.makeFloatType(32);
7872 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007873 break;
7874 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007875 typeId = builder.makeIntType(32);
7876 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007877 break;
7878 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007879 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007880 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007881 break;
7882 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007883 typeId = builder.makeIntType(32);
7884 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007885 break;
7886 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007887 typeId = builder.makeIntType(32);
7888 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007889 break;
7890 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007891 typeId = builder.makeIntType(32);
7892 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007893 break;
7894 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007895 typeId = builder.makeIntType(32);
7896 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007897 break;
7898 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007899 typeId = builder.makeIntType(32);
7900 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007901 break;
7902 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007903 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7904 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007905 break;
7906 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007907 typeId = builder.makeBoolType();
7908 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007909 break;
7910 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007911 typeId = builder.makeBoolType();
7912 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007913 break;
7914 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007915 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7916 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007917 break;
7918 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007919 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7920 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007921 break;
7922 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007923 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7924 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007925 break;
7926 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007927 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7928 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007929 break;
7930 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007931 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007932 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007933 break;
7934 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007935 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007936 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007937 break;
Chao Chen3c366992018-09-19 11:41:59 -07007938 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7939 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7940 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007941 case glslang::EOpCooperativeMatrixMulAdd:
7942 opCode = spv::OpCooperativeMatrixMulAddNV;
7943 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007944#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007945 default:
7946 return 0;
7947 }
7948
7949 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007950 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007951 // Use an extended instruction from the standard library.
7952 // Construct the call arguments, without modifying the original operands vector.
7953 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7954 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007955 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007956 } else if (opCode == spv::OpDot && !isFloat) {
7957 // int dot(int, int)
7958 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7959 const int componentCount = builder.getNumComponents(operands[0]);
7960 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7961 builder.setPrecision(mulOp, precision);
7962 id = builder.createCompositeExtract(mulOp, typeId, 0);
7963 for (int i = 1; i < componentCount; ++i) {
7964 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007965 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007966 }
John Kessenich2359bd02015-12-06 19:29:11 -07007967 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007968 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007969 case 0:
7970 // should all be handled by visitAggregate and createNoArgOperation
7971 assert(0);
7972 return 0;
7973 case 1:
7974 // should all be handled by createUnaryOperation
7975 assert(0);
7976 return 0;
7977 case 2:
7978 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7979 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007980 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007981 // anything 3 or over doesn't have l-value operands, so all should be consumed
7982 assert(consumedOperands == operands.size());
7983 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007984 break;
7985 }
7986 }
7987
John Kessenichb9197c82019-08-11 07:41:45 -06007988#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007989 // Decode the return types that were structures
7990 switch (op) {
7991 case glslang::EOpAddCarry:
7992 case glslang::EOpSubBorrow:
7993 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7994 id = builder.createCompositeExtract(id, typeId0, 0);
7995 break;
7996 case glslang::EOpUMulExtended:
7997 case glslang::EOpIMulExtended:
7998 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7999 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
8000 break;
8001 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08008002 {
8003 assert(operands.size() == 2);
8004 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
8005 // "exp" is floating-point type (from HLSL intrinsic)
8006 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
8007 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
8008 builder.createStore(member1, operands[1]);
8009 } else
8010 // "exp" is integer type (from GLSL built-in function)
8011 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
8012 id = builder.createCompositeExtract(id, typeId0, 0);
8013 }
John Kessenich55e7d112015-11-15 21:33:39 -07008014 break;
8015 default:
8016 break;
8017 }
John Kessenichb9197c82019-08-11 07:41:45 -06008018#endif
John Kessenich55e7d112015-11-15 21:33:39 -07008019
John Kessenich32cfd492016-02-02 12:37:46 -07008020 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06008021}
8022
Rex Xu9d93a232016-05-05 12:30:44 +08008023// Intrinsics with no arguments (or no return value, and no precision).
8024spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06008025{
Jeff Bolz36831c92018-09-05 10:11:41 -05008026 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07008027 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
8028 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06008029
8030 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06008031 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008032 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05008033 if (glslangIntermediate->usingVulkanMemoryModel()) {
8034 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8035 spv::MemorySemanticsOutputMemoryKHRMask |
8036 spv::MemorySemanticsAcquireReleaseMask);
8037 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
8038 } else {
8039 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
8040 }
John Kessenich82979362017-12-11 04:02:24 -07008041 } else {
8042 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8043 spv::MemorySemanticsWorkgroupMemoryMask |
8044 spv::MemorySemanticsAcquireReleaseMask);
8045 }
John Kessenich140f3df2015-06-26 16:58:36 -06008046 return 0;
8047 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05008048 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
8049 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008050 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008051 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05008052 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
8053 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008054 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008055 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05008056 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
8057 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008058 return 0;
8059 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008060 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
8061 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008062 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06008063#ifndef GLSLANG_WEB
8064 case glslang::EOpMemoryBarrierAtomicCounter:
8065 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
8066 spv::MemorySemanticsAcquireReleaseMask);
8067 return 0;
8068 case glslang::EOpMemoryBarrierImage:
8069 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8070 spv::MemorySemanticsAcquireReleaseMask);
8071 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008072 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008073 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008074 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008075 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008076 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008077 case glslang::EOpDeviceMemoryBarrier:
8078 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8079 spv::MemorySemanticsImageMemoryMask |
8080 spv::MemorySemanticsAcquireReleaseMask);
8081 return 0;
8082 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8083 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8084 spv::MemorySemanticsImageMemoryMask |
8085 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008086 return 0;
8087 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008088 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8089 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008090 return 0;
8091 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008092 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8093 spv::MemorySemanticsWorkgroupMemoryMask |
8094 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008095 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008096 case glslang::EOpSubgroupBarrier:
8097 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8098 spv::MemorySemanticsAcquireReleaseMask);
8099 return spv::NoResult;
8100 case glslang::EOpSubgroupMemoryBarrier:
8101 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8102 spv::MemorySemanticsAcquireReleaseMask);
8103 return spv::NoResult;
8104 case glslang::EOpSubgroupMemoryBarrierBuffer:
8105 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8106 spv::MemorySemanticsAcquireReleaseMask);
8107 return spv::NoResult;
8108 case glslang::EOpSubgroupMemoryBarrierImage:
8109 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8110 spv::MemorySemanticsAcquireReleaseMask);
8111 return spv::NoResult;
8112 case glslang::EOpSubgroupMemoryBarrierShared:
8113 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8114 spv::MemorySemanticsAcquireReleaseMask);
8115 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008116
8117 case glslang::EOpEmitVertex:
8118 builder.createNoResultOp(spv::OpEmitVertex);
8119 return 0;
8120 case glslang::EOpEndPrimitive:
8121 builder.createNoResultOp(spv::OpEndPrimitive);
8122 return 0;
8123
John Kessenich66011cb2018-03-06 16:12:04 -07008124 case glslang::EOpSubgroupElect: {
8125 std::vector<spv::Id> operands;
8126 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8127 }
Rex Xu9d93a232016-05-05 12:30:44 +08008128 case glslang::EOpTime:
8129 {
8130 std::vector<spv::Id> args; // Dummy arguments
8131 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8132 return builder.setPrecision(id, precision);
8133 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008134 case glslang::EOpIgnoreIntersection:
8135 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008136 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008137 case glslang::EOpTerminateRay:
8138 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008139 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008140 case glslang::EOpRayQueryInitialize:
8141 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8142 return 0;
8143 case glslang::EOpRayQueryTerminate:
8144 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8145 return 0;
8146 case glslang::EOpRayQueryGenerateIntersection:
8147 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8148 return 0;
8149 case glslang::EOpRayQueryConfirmIntersection:
8150 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8151 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008152 case glslang::EOpBeginInvocationInterlock:
8153 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8154 return 0;
8155 case glslang::EOpEndInvocationInterlock:
8156 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8157 return 0;
8158
Jeff Bolzba6170b2019-07-01 09:23:23 -05008159 case glslang::EOpIsHelperInvocation:
8160 {
8161 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008162 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8163 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8164 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008165 }
8166
amhagan91fb0092019-07-10 21:14:38 -04008167 case glslang::EOpReadClockSubgroupKHR: {
8168 std::vector<spv::Id> args;
8169 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8170 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8171 builder.addCapability(spv::CapabilityShaderClockKHR);
8172 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8173 }
8174
8175 case glslang::EOpReadClockDeviceKHR: {
8176 std::vector<spv::Id> args;
8177 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8178 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8179 builder.addCapability(spv::CapabilityShaderClockKHR);
8180 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8181 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008182#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008183 default:
John Kessenich155d3512019-08-08 23:29:20 -06008184 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008185 }
John Kessenich155d3512019-08-08 23:29:20 -06008186
8187 logger->missingFunctionality("unknown operation with no arguments");
8188
8189 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008190}
8191
8192spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8193{
John Kessenich2f273362015-07-18 22:34:27 -06008194 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008195 spv::Id id;
8196 if (symbolValues.end() != iter) {
8197 id = iter->second;
8198 return id;
8199 }
8200
8201 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008202 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008203 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008204 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008205 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008206 if (forcedType.second != spv::NoType)
8207 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008208
Rex Xuc884b4a2016-06-29 15:03:44 +08008209 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008210 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8211 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8212 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008213#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008214 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008215 if (symbol->getQualifier().hasComponent())
8216 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8217 if (symbol->getQualifier().hasIndex())
8218 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008219#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008220 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008221 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008222 // atomic counters use this:
8223 if (symbol->getQualifier().hasOffset())
8224 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008225 }
8226
scygan2c864272016-05-18 18:09:17 +02008227 if (symbol->getQualifier().hasLocation())
8228 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008229 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008230 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008231 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008232 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008233 }
John Kessenich140f3df2015-06-26 16:58:36 -06008234 if (symbol->getQualifier().hasSet())
8235 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008236 else if (IsDescriptorResource(symbol->getType())) {
8237 // default to 0
8238 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8239 }
John Kessenich140f3df2015-06-26 16:58:36 -06008240 if (symbol->getQualifier().hasBinding())
8241 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008242 else if (IsDescriptorResource(symbol->getType())) {
8243 // default to 0
8244 builder.addDecoration(id, spv::DecorationBinding, 0);
8245 }
John Kessenich6c292d32016-02-15 20:58:50 -07008246 if (symbol->getQualifier().hasAttachment())
8247 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008248 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008249 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008250 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008251 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008252 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8253 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8254 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8255 }
8256 if (symbol->getQualifier().hasXfbOffset())
8257 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008258 }
8259
John Kessenichb9197c82019-08-11 07:41:45 -06008260 // add built-in variable decoration
8261 if (builtIn != spv::BuiltInMax) {
8262 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8263 }
8264
8265#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008266 if (symbol->getType().isImage()) {
8267 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008268 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8269 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008270 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008271 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008272 }
8273
chaoc0ad6a4e2016-12-19 16:29:34 -08008274 if (builtIn == spv::BuiltInSampleMask) {
8275 spv::Decoration decoration;
8276 // GL_NV_sample_mask_override_coverage extension
8277 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008278 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008279 else
8280 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008281 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008282 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008283 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008284 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8285 }
8286 }
chaoc771d89f2017-01-13 01:10:53 -08008287 else if (builtIn == spv::BuiltInLayer) {
8288 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008289 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008290 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008291 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8292 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8293 }
John Kessenichb41bff62017-08-11 13:07:17 -06008294 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008295 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8296 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008297 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8298 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8299 }
8300 }
8301
chaoc6e5acae2016-12-20 13:28:52 -08008302 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008303 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008304 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008305 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8306 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008307 if (symbol->getQualifier().pervertexNV) {
8308 builder.addDecoration(id, spv::DecorationPerVertexNV);
8309 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8310 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8311 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008312
John Kessenich5d610ee2018-03-07 18:05:55 -07008313 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8314 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8315 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8316 symbol->getType().getQualifier().semanticName);
8317 }
8318
John Kessenich7015bd62019-08-01 03:28:08 -06008319 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008320 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8321 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008322 }
John Kessenichb9197c82019-08-11 07:41:45 -06008323#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008324
John Kessenich140f3df2015-06-26 16:58:36 -06008325 return id;
8326}
8327
John Kessenicha28f7a72019-08-06 07:00:58 -06008328#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008329// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8330void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8331{
8332 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008333 if (qualifier.perPrimitiveNV) {
8334 // Need to add capability/extension for fragment shader.
8335 // Mesh shader already adds this by default.
8336 if (glslangIntermediate->getStage() == EShLangFragment) {
8337 builder.addCapability(spv::CapabilityMeshShadingNV);
8338 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8339 }
Chao Chen3c366992018-09-19 11:41:59 -07008340 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008341 }
Chao Chen3c366992018-09-19 11:41:59 -07008342 if (qualifier.perViewNV)
8343 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8344 if (qualifier.perTaskNV)
8345 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8346 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008347 if (qualifier.perPrimitiveNV) {
8348 // Need to add capability/extension for fragment shader.
8349 // Mesh shader already adds this by default.
8350 if (glslangIntermediate->getStage() == EShLangFragment) {
8351 builder.addCapability(spv::CapabilityMeshShadingNV);
8352 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8353 }
Chao Chen3c366992018-09-19 11:41:59 -07008354 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008355 }
Chao Chen3c366992018-09-19 11:41:59 -07008356 if (qualifier.perViewNV)
8357 builder.addDecoration(id, spv::DecorationPerViewNV);
8358 if (qualifier.perTaskNV)
8359 builder.addDecoration(id, spv::DecorationPerTaskNV);
8360 }
8361}
8362#endif
8363
John Kessenich55e7d112015-11-15 21:33:39 -07008364// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008365// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008366//
8367// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8368//
8369// Recursively walk the nodes. The nodes form a tree whose leaves are
8370// regular constants, which themselves are trees that createSpvConstant()
8371// recursively walks. So, this function walks the "top" of the tree:
8372// - emit specialization constant-building instructions for specConstant
8373// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008374spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008375{
John Kessenich7cc0e282016-03-20 00:46:02 -06008376 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008377
qining4f4bb812016-04-03 23:55:17 -04008378 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008379 if (! node.getQualifier().specConstant) {
8380 // hand off to the non-spec-constant path
8381 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8382 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008383 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8384 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8385 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008386 }
8387
8388 // We now know we have a specialization constant to build
8389
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008390 // Extra capabilities may be needed.
8391 if (node.getType().contains8BitInt())
8392 builder.addCapability(spv::CapabilityInt8);
8393 if (node.getType().contains16BitFloat())
8394 builder.addCapability(spv::CapabilityFloat16);
8395 if (node.getType().contains16BitInt())
8396 builder.addCapability(spv::CapabilityInt16);
8397 if (node.getType().contains64BitInt())
8398 builder.addCapability(spv::CapabilityInt64);
8399 if (node.getType().containsDouble())
8400 builder.addCapability(spv::CapabilityFloat64);
8401
John Kessenichd94c0032016-05-30 19:29:40 -06008402 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008403 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8404 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8405 std::vector<spv::Id> dimConstId;
8406 for (int dim = 0; dim < 3; ++dim) {
8407 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8408 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008409 if (specConst) {
8410 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8411 glslangIntermediate->getLocalSizeSpecId(dim));
8412 }
qining4f4bb812016-04-03 23:55:17 -04008413 }
8414 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8415 }
8416
8417 // An AST node labelled as specialization constant should be a symbol node.
8418 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8419 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008420 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008421 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008422 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8423 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8424 // will set the builder into spec constant op instruction generating mode.
8425 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008426 result = accessChainLoad(sub_tree->getType());
8427 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008428 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008429 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008430 } else {
8431 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008432 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008433 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008434 builder.addName(result, sn->getName().c_str());
8435 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008436 }
qining4f4bb812016-04-03 23:55:17 -04008437
8438 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8439 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008440 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008441 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008442}
8443
John Kessenich140f3df2015-06-26 16:58:36 -06008444// Use 'consts' as the flattened glslang source of scalar constants to recursively
8445// build the aggregate SPIR-V constant.
8446//
8447// If there are not enough elements present in 'consts', 0 will be substituted;
8448// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8449//
John Kessenich8985fc92020-03-03 10:25:07 -07008450spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8451 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008452{
8453 // vector of constants for SPIR-V
8454 std::vector<spv::Id> spvConsts;
8455
8456 // Type is used for struct and array constants
8457 spv::Id typeId = convertGlslangToSpvType(glslangType);
8458
8459 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008460 glslang::TType elementType(glslangType, 0);
8461 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008462 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008463 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008464 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008465 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008466 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008467 } else if (glslangType.isCoopMat()) {
8468 glslang::TType componentType(glslangType.getBasicType());
8469 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008470 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008471 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8472 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008473 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008474 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008475 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8476 bool zero = nextConst >= consts.size();
8477 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008478 case glslang::EbtInt:
8479 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8480 break;
8481 case glslang::EbtUint:
8482 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8483 break;
8484 case glslang::EbtFloat:
8485 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8486 break;
8487 case glslang::EbtBool:
8488 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8489 break;
8490#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008491 case glslang::EbtInt8:
8492 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8493 break;
8494 case glslang::EbtUint8:
8495 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8496 break;
8497 case glslang::EbtInt16:
8498 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8499 break;
8500 case glslang::EbtUint16:
8501 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8502 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008503 case glslang::EbtInt64:
8504 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8505 break;
8506 case glslang::EbtUint64:
8507 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8508 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008509 case glslang::EbtDouble:
8510 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8511 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008512 case glslang::EbtFloat16:
8513 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8514 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008515#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008516 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008517 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008518 break;
8519 }
8520 ++nextConst;
8521 }
8522 } else {
8523 // we have a non-aggregate (scalar) constant
8524 bool zero = nextConst >= consts.size();
8525 spv::Id scalar = 0;
8526 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008527 case glslang::EbtInt:
8528 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8529 break;
8530 case glslang::EbtUint:
8531 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8532 break;
8533 case glslang::EbtFloat:
8534 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8535 break;
8536 case glslang::EbtBool:
8537 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8538 break;
8539#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008540 case glslang::EbtInt8:
8541 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8542 break;
8543 case glslang::EbtUint8:
8544 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8545 break;
8546 case glslang::EbtInt16:
8547 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8548 break;
8549 case glslang::EbtUint16:
8550 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8551 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008552 case glslang::EbtInt64:
8553 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8554 break;
8555 case glslang::EbtUint64:
8556 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8557 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008558 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008559 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008560 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008561 case glslang::EbtFloat16:
8562 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8563 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008564 case glslang::EbtReference:
8565 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8566 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8567 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008568#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008569 case glslang::EbtString:
8570 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8571 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008572 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008573 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008574 break;
8575 }
8576 ++nextConst;
8577 return scalar;
8578 }
8579
8580 return builder.makeCompositeConstant(typeId, spvConsts);
8581}
8582
John Kessenich7c1aa102015-10-15 13:29:11 -06008583// Return true if the node is a constant or symbol whose reading has no
8584// non-trivial observable cost or effect.
8585bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8586{
8587 // don't know what this is
8588 if (node == nullptr)
8589 return false;
8590
8591 // a constant is safe
8592 if (node->getAsConstantUnion() != nullptr)
8593 return true;
8594
8595 // not a symbol means non-trivial
8596 if (node->getAsSymbolNode() == nullptr)
8597 return false;
8598
8599 // a symbol, depends on what's being read
8600 switch (node->getType().getQualifier().storage) {
8601 case glslang::EvqTemporary:
8602 case glslang::EvqGlobal:
8603 case glslang::EvqIn:
8604 case glslang::EvqInOut:
8605 case glslang::EvqConst:
8606 case glslang::EvqConstReadOnly:
8607 case glslang::EvqUniform:
8608 return true;
8609 default:
8610 return false;
8611 }
qining25262b32016-05-06 17:25:16 -04008612}
John Kessenich7c1aa102015-10-15 13:29:11 -06008613
8614// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008615// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008616// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008617// Return true if trivial.
8618bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8619{
8620 if (node == nullptr)
8621 return false;
8622
John Kessenich84cc15f2017-05-24 16:44:47 -06008623 // count non scalars as trivial, as well as anything coming from HLSL
8624 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008625 return true;
8626
John Kessenich7c1aa102015-10-15 13:29:11 -06008627 // symbols and constants are trivial
8628 if (isTrivialLeaf(node))
8629 return true;
8630
8631 // otherwise, it needs to be a simple operation or one or two leaf nodes
8632
8633 // not a simple operation
8634 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8635 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8636 if (binaryNode == nullptr && unaryNode == nullptr)
8637 return false;
8638
8639 // not on leaf nodes
8640 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8641 return false;
8642
8643 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8644 return false;
8645 }
8646
8647 switch (node->getAsOperator()->getOp()) {
8648 case glslang::EOpLogicalNot:
8649 case glslang::EOpConvIntToBool:
8650 case glslang::EOpConvUintToBool:
8651 case glslang::EOpConvFloatToBool:
8652 case glslang::EOpConvDoubleToBool:
8653 case glslang::EOpEqual:
8654 case glslang::EOpNotEqual:
8655 case glslang::EOpLessThan:
8656 case glslang::EOpGreaterThan:
8657 case glslang::EOpLessThanEqual:
8658 case glslang::EOpGreaterThanEqual:
8659 case glslang::EOpIndexDirect:
8660 case glslang::EOpIndexDirectStruct:
8661 case glslang::EOpLogicalXor:
8662 case glslang::EOpAny:
8663 case glslang::EOpAll:
8664 return true;
8665 default:
8666 return false;
8667 }
8668}
8669
8670// Emit short-circuiting code, where 'right' is never evaluated unless
8671// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008672spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8673 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008674{
8675 spv::Id boolTypeId = builder.makeBoolType();
8676
8677 // emit left operand
8678 builder.clearAccessChain();
8679 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008680 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008681
8682 // Operands to accumulate OpPhi operands
8683 std::vector<spv::Id> phiOperands;
8684 // accumulate left operand's phi information
8685 phiOperands.push_back(leftId);
8686 phiOperands.push_back(builder.getBuildPoint()->getId());
8687
8688 // Make the two kinds of operation symmetric with a "!"
8689 // || => emit "if (! left) result = right"
8690 // && => emit "if ( left) result = right"
8691 //
8692 // TODO: this runtime "not" for || could be avoided by adding functionality
8693 // to 'builder' to have an "else" without an "then"
8694 if (op == glslang::EOpLogicalOr)
8695 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8696
8697 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008698 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008699
8700 // emit right operand as the "then" part of the "if"
8701 builder.clearAccessChain();
8702 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008703 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008704
8705 // accumulate left operand's phi information
8706 phiOperands.push_back(rightId);
8707 phiOperands.push_back(builder.getBuildPoint()->getId());
8708
8709 // finish the "if"
8710 ifBuilder.makeEndIf();
8711
8712 // phi together the two results
8713 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8714}
8715
John Kessenicha28f7a72019-08-06 07:00:58 -06008716#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008717// Return type Id of the imported set of extended instructions corresponds to the name.
8718// Import this set if it has not been imported yet.
8719spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8720{
8721 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8722 return extBuiltinMap[name];
8723 else {
Rex Xu51596642016-09-21 18:56:12 +08008724 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008725 spv::Id extBuiltins = builder.import(name);
8726 extBuiltinMap[name] = extBuiltins;
8727 return extBuiltins;
8728 }
8729}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008730#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008731
John Kessenich140f3df2015-06-26 16:58:36 -06008732}; // end anonymous namespace
8733
8734namespace glslang {
8735
John Kessenich68d78fd2015-07-12 19:28:10 -06008736void GetSpirvVersion(std::string& version)
8737{
John Kessenich9e55f632015-07-15 10:03:39 -06008738 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008739 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008740 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008741 version = buf;
8742}
8743
John Kessenicha372a3e2017-11-02 22:32:14 -06008744// For low-order part of the generator's magic number. Bump up
8745// when there is a change in the style (e.g., if SSA form changes,
8746// or a different instruction sequence to do something gets used).
8747int GetSpirvGeneratorVersion()
8748{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008749 // return 1; // start
8750 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008751 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008752 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008753 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008754 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8755 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008756 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008757 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008758 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8759 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008760}
8761
John Kessenich140f3df2015-06-26 16:58:36 -06008762// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008763void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008764{
8765 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008766 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008767 if (out.fail())
8768 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008769 for (int i = 0; i < (int)spirv.size(); ++i) {
8770 unsigned int word = spirv[i];
8771 out.write((const char*)&word, 4);
8772 }
8773 out.close();
8774}
8775
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008776// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008777void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008778{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008779#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008780 std::ofstream out;
8781 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008782 if (out.fail())
8783 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008784 out << "\t// " <<
8785 GetSpirvGeneratorVersion() <<
8786 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8787 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008788 if (varName != nullptr) {
8789 out << "\t #pragma once" << std::endl;
8790 out << "const uint32_t " << varName << "[] = {" << std::endl;
8791 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008792 const int WORDS_PER_LINE = 8;
8793 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8794 out << "\t";
8795 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8796 const unsigned int word = spirv[i + j];
8797 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8798 if (i + j + 1 < (int)spirv.size()) {
8799 out << ",";
8800 }
8801 }
8802 out << std::endl;
8803 }
Flavio15017db2017-02-15 14:29:33 -08008804 if (varName != nullptr) {
8805 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008806 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008807 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008808 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008809#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008810}
8811
John Kessenich140f3df2015-06-26 16:58:36 -06008812//
8813// Set up the glslang traversal
8814//
John Kessenich4e11b612018-08-30 16:56:59 -06008815void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008816{
Lei Zhang17535f72016-05-04 15:55:59 -04008817 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008818 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008819}
8820
John Kessenich4e11b612018-08-30 16:56:59 -06008821void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008822 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008823{
John Kessenich140f3df2015-06-26 16:58:36 -06008824 TIntermNode* root = intermediate.getTreeRoot();
8825
8826 if (root == 0)
8827 return;
8828
John Kessenich4e11b612018-08-30 16:56:59 -06008829 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008830 if (options == nullptr)
8831 options = &defaultOptions;
8832
John Kessenich4e11b612018-08-30 16:56:59 -06008833 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008834
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008835 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008836 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008837 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008838 it.dumpSpv(spirv);
8839
GregFfb03a552018-03-29 11:49:14 -06008840#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008841 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8842 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008843 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008844 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8845 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008846 prelegalization = false;
8847 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008848 else if (options->stripDebugInfo) {
8849 // Strip debug info even if optimization is disabled.
8850 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8851 }
John Kessenich717c80a2018-08-23 15:17:10 -06008852
John Kessenich4e11b612018-08-30 16:56:59 -06008853 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008854 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008855
John Kessenich717c80a2018-08-23 15:17:10 -06008856 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008857 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008858
GregFcd1f1692017-09-21 18:40:22 -06008859#endif
8860
John Kessenich4e11b612018-08-30 16:56:59 -06008861 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008862}
8863
8864}; // end namespace glslang