blob: 9670c72d43da560accb914b4722efb97322a0cc1 [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);
Jeff Bolz36831c92018-09-05 10:11:41 -0500152 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
153 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
154 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
155 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100156 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700157 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700158 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
159 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700160 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600161 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600162 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600163 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600164 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600165 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
166 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
167 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600168 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600169 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600170 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600171 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600172 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
173 glslang::TLayoutPacking, const glslang::TQualifier&);
174 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
175 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700176 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700177 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800178 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600179 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700180 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700181 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
182 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700183 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
184 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100185 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600186
John Kessenich6fccb3c2016-09-19 16:01:41 -0600187 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600188 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600189 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600190 void makeFunctions(const glslang::TIntermSequence&);
191 void makeGlobalInitializers(const glslang::TIntermSequence&);
192 void visitFunctions(const glslang::TIntermSequence&);
193 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700194 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
195 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600196 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
197 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600198 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
199
John Kessenichead86222018-03-28 18:01:20 -0600200 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
201 glslang::TBasicType typeProxy, bool reduceComparison = true);
202 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
203 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700204 glslang::TBasicType typeProxy,
205 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600206 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
207 glslang::TBasicType typeProxy);
208 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
209 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600210 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600211 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700212 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
213 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
214 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
215 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
216 glslang::TBasicType typeProxy);
217 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
218 spv::Id typeId, std::vector<spv::Id>& operands);
219 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
220 glslang::TBasicType typeProxy);
221 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
222 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800223 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600224 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700225 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400226 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700227 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
228 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600229 bool isTrivialLeaf(const glslang::TIntermTyped* node);
230 bool isTrivial(const glslang::TIntermTyped* node);
231 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800232 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400233 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600234 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500235 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600236
John Kessenich121853f2017-05-31 17:11:16 -0600237 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600239 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700240 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600241 int sequenceDepth;
242
Lei Zhang17535f72016-05-04 15:55:59 -0400243 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400244
John Kessenich140f3df2015-06-26 16:58:36 -0600245 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
246 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700247 bool inEntryPoint;
248 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700249 bool linkageOnly; // true when visiting the set of objects in the AST present only for
250 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700251 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600252 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600253 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600254 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500255 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800256 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600257
John Kessenich2f273362015-07-18 22:34:27 -0600258 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700259 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
260 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600261 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700262 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700263 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800264 std::unordered_map<int, std::vector<int>> memberRemapper;
265 // for mapping glslang symbol struct to symbol Id
266 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600267 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700268 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600269 // Map pointee types for EbtReference to their forward pointers
270 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600271 // Type forcing, for when SPIR-V wants a different type than the AST,
272 // requiring local translation to and from SPIR-V type on every access.
273 // Maps <builtin-variable-id -> AST-required-type-id>
274 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600275};
276
277//
278// Helper functions for translating glslang representations to SPIR-V enumerants.
279//
280
281// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700282spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600283{
John Kessenich155d3512019-08-08 23:29:20 -0600284#ifdef GLSLANG_WEB
285 return spv::SourceLanguageESSL;
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -0400286#elif defined(GLSLANG_ANGLE)
287 return spv::SourceLanguageGLSL;
John Kessenich155d3512019-08-08 23:29:20 -0600288#endif
289
John Kessenich66e2faf2016-03-12 18:34:36 -0700290 switch (source) {
291 case glslang::EShSourceGlsl:
292 switch (profile) {
293 case ENoProfile:
294 case ECoreProfile:
295 case ECompatibilityProfile:
296 return spv::SourceLanguageGLSL;
297 case EEsProfile:
298 return spv::SourceLanguageESSL;
299 default:
300 return spv::SourceLanguageUnknown;
301 }
302 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600303 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 default:
305 return spv::SourceLanguageUnknown;
306 }
307}
308
309// Translate glslang language (stage) to SPIR-V execution model.
310spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
311{
312 switch (stage) {
313 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600314 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600315 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600316#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600317 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
318 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
319 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400320 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
321 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
322 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
323 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
324 case EShLangMiss: return spv::ExecutionModelMissKHR;
325 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700326 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
327 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
328#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600329 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700330 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600331 return spv::ExecutionModelFragment;
332 }
333}
334
John Kessenich140f3df2015-06-26 16:58:36 -0600335// Translate glslang sampler type to SPIR-V dimensionality.
336spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
337{
338 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700339 case glslang::Esd1D: return spv::Dim1D;
340 case glslang::Esd2D: return spv::Dim2D;
341 case glslang::Esd3D: return spv::Dim3D;
342 case glslang::EsdCube: return spv::DimCube;
343 case glslang::EsdRect: return spv::DimRect;
344 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700345 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return spv::Dim2D;
349 }
350}
351
John Kessenichf6640762016-08-01 19:44:00 -0600352// Translate glslang precision to SPIR-V precision decorations.
353spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600354{
John Kessenichf6640762016-08-01 19:44:00 -0600355 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700356 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600357 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 default:
359 return spv::NoPrecision;
360 }
361}
362
John Kessenichf6640762016-08-01 19:44:00 -0600363// Translate glslang type to SPIR-V precision decorations.
364spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
365{
366 return TranslatePrecisionDecoration(type.getQualifier().precision);
367}
368
John Kessenich140f3df2015-06-26 16:58:36 -0600369// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600370spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600371{
372 if (type.getBasicType() == glslang::EbtBlock) {
373 switch (type.getQualifier().storage) {
374 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600375 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 case glslang::EvqVaryingIn: return spv::DecorationBlock;
377 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600378#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400379 case glslang::EvqPayload: return spv::DecorationBlock;
380 case glslang::EvqPayloadIn: return spv::DecorationBlock;
381 case glslang::EvqHitAttr: return spv::DecorationBlock;
382 case glslang::EvqCallableData: return spv::DecorationBlock;
383 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700384#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600385 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700386 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600387 break;
388 }
389 }
390
John Kessenich4016e382016-07-15 11:53:56 -0600391 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600392}
393
Rex Xu1da878f2016-02-21 20:59:01 +0800394// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700395void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
396 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800397{
Jeff Bolz36831c92018-09-05 10:11:41 -0500398 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600399 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500400 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600401 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500402 memory.push_back(spv::DecorationVolatile);
403 memory.push_back(spv::DecorationCoherent);
404 }
John Kessenich14b85d32018-06-04 15:36:03 -0600405 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600406 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800407 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600408 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800409 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600410 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800411 memory.push_back(spv::DecorationNonReadable);
412}
413
John Kessenich140f3df2015-06-26 16:58:36 -0600414// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700415spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600416{
417 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700418 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600419 case glslang::ElmRowMajor:
420 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700421 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600422 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700423 default:
424 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600425 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600426 }
427 } else {
428 switch (type.getBasicType()) {
429 default:
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431 break;
432 case glslang::EbtBlock:
433 switch (type.getQualifier().storage) {
434 case glslang::EvqUniform:
435 case glslang::EvqBuffer:
436 switch (type.getQualifier().layoutPacking) {
437 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600438 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
439 default:
John Kessenich4016e382016-07-15 11:53:56 -0600440 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600441 }
442 case glslang::EvqVaryingIn:
443 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700444 if (type.getQualifier().isTaskMemory()) {
445 switch (type.getQualifier().layoutPacking) {
446 case glslang::ElpShared: return spv::DecorationGLSLShared;
447 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
448 default: break;
449 }
450 } else {
451 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
452 }
John Kessenich4016e382016-07-15 11:53:56 -0600453 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600454#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400455 case glslang::EvqPayload:
456 case glslang::EvqPayloadIn:
457 case glslang::EvqHitAttr:
458 case glslang::EvqCallableData:
459 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700460 return spv::DecorationMax;
461#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600462 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700463 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600464 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600465 }
466 }
467 }
468}
469
470// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600471// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700472// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800473spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600474{
Rex Xubbceed72016-05-21 09:40:44 +0800475 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700476 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600477 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600478 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700479 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700480 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600481 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600482 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800483 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800484 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800485 }
Rex Xubbceed72016-05-21 09:40:44 +0800486 else
John Kessenich4016e382016-07-15 11:53:56 -0600487 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800488}
489
490// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600491// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800492// should be applied.
493spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
494{
John Kessenichb9197c82019-08-11 07:41:45 -0600495 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600496 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600497#ifndef GLSLANG_WEB
498 else if (qualifier.patch)
499 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700500 else if (qualifier.sample) {
501 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600502 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600503 }
504#endif
505
506 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600507}
508
John Kessenich92187592016-02-01 13:45:25 -0700509// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700510spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600511{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700512 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600513 return spv::DecorationInvariant;
514 else
John Kessenich4016e382016-07-15 11:53:56 -0600515 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600516}
517
qining9220dbb2016-05-04 17:34:38 -0400518// If glslang type is noContraction, return SPIR-V NoContraction decoration.
519spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
520{
John Kessenichb9197c82019-08-11 07:41:45 -0600521#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600522 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400523 return spv::DecorationNoContraction;
524 else
John Kessenichb9197c82019-08-11 07:41:45 -0600525#endif
John Kessenich4016e382016-07-15 11:53:56 -0600526 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400527}
528
John Kessenich5611c6d2018-04-05 11:25:02 -0600529// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
530spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
531{
John Kessenichb9197c82019-08-11 07:41:45 -0600532#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600533 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600534 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600535 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
536 return spv::DecorationNonUniformEXT;
537 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600538#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600539 return spv::DecorationMax;
540}
541
John Kessenichb9197c82019-08-11 07:41:45 -0600542spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
543 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500544{
Jeff Bolz36831c92018-09-05 10:11:41 -0500545 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600546
547#ifndef GLSLANG_WEB
548 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
549 return mask;
550
Daniel Kochdb32b242020-03-17 20:42:47 -0400551 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
553 spv::MemoryAccessMakePointerVisibleKHRMask;
554 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400555
Jeff Bolz36831c92018-09-05 10:11:41 -0500556 if (coherentFlags.nonprivate) {
557 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
558 }
559 if (coherentFlags.volatil) {
560 mask = mask | spv::MemoryAccessVolatileMask;
561 }
562 if (mask != spv::MemoryAccessMaskNone) {
563 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
564 }
John Kessenichb9197c82019-08-11 07:41:45 -0600565#endif
566
Jeff Bolz36831c92018-09-05 10:11:41 -0500567 return mask;
568}
569
John Kessenichb9197c82019-08-11 07:41:45 -0600570spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
571 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500572{
Jeff Bolz36831c92018-09-05 10:11:41 -0500573 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600574
575#ifndef GLSLANG_WEB
576 if (!glslangIntermediate->usingVulkanMemoryModel())
577 return mask;
578
Jeff Bolz36831c92018-09-05 10:11:41 -0500579 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400580 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500581 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
582 spv::ImageOperandsMakeTexelVisibleKHRMask;
583 }
584 if (coherentFlags.nonprivate) {
585 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
586 }
587 if (coherentFlags.volatil) {
588 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
589 }
590 if (mask != spv::ImageOperandsMaskNone) {
591 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
592 }
John Kessenichb9197c82019-08-11 07:41:45 -0600593#endif
594
Jeff Bolz36831c92018-09-05 10:11:41 -0500595 return mask;
596}
597
598spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
599{
John Kessenichb9197c82019-08-11 07:41:45 -0600600 spv::Builder::AccessChain::CoherentFlags flags = {};
601#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500602 flags.coherent = type.getQualifier().coherent;
603 flags.devicecoherent = type.getQualifier().devicecoherent;
604 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
605 // shared variables are implicitly workgroupcoherent in GLSL.
606 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
607 type.getQualifier().storage == glslang::EvqShared;
608 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400609 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600610 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500611 // *coherent variables are implicitly nonprivate in GLSL
612 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400613 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600614 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500615 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600616#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500617 return flags;
618}
619
John Kessenichb9197c82019-08-11 07:41:45 -0600620spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
621 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500622{
John Kessenichb9197c82019-08-11 07:41:45 -0600623 spv::Scope scope = spv::ScopeMax;
624
625#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600626 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500627 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
628 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
629 } else if (coherentFlags.devicecoherent) {
630 scope = spv::ScopeDevice;
631 } else if (coherentFlags.queuefamilycoherent) {
632 scope = spv::ScopeQueueFamilyKHR;
633 } else if (coherentFlags.workgroupcoherent) {
634 scope = spv::ScopeWorkgroup;
635 } else if (coherentFlags.subgroupcoherent) {
636 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400637 } else if (coherentFlags.shadercallcoherent) {
638 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500639 }
640 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
641 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
642 }
John Kessenichb9197c82019-08-11 07:41:45 -0600643#endif
644
Jeff Bolz36831c92018-09-05 10:11:41 -0500645 return scope;
646}
647
David Netoa901ffe2016-06-08 14:11:40 +0100648// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
649// associated capabilities when required. For some built-in variables, a capability
650// is generated only when using the variable in an executable instruction, but not when
651// just declaring a struct member variable with it. This is true for PointSize,
652// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700653spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
654 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600655{
656 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700657 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600658#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600659 // Defer adding the capability until the built-in is actually used.
660 if (! memberDeclaration) {
661 switch (glslangIntermediate->getStage()) {
662 case EShLangGeometry:
663 builder.addCapability(spv::CapabilityGeometryPointSize);
664 break;
665 case EShLangTessControl:
666 case EShLangTessEvaluation:
667 builder.addCapability(spv::CapabilityTessellationPointSize);
668 break;
669 default:
670 break;
671 }
John Kessenich92187592016-02-01 13:45:25 -0700672 }
John Kessenich155d3512019-08-08 23:29:20 -0600673#endif
John Kessenich92187592016-02-01 13:45:25 -0700674 return spv::BuiltInPointSize;
675
John Kessenicha28f7a72019-08-06 07:00:58 -0600676 case glslang::EbvPosition: return spv::BuiltInPosition;
677 case glslang::EbvVertexId: return spv::BuiltInVertexId;
678 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
679 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
680 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
681
682 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
683 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
684 case glslang::EbvFace: return spv::BuiltInFrontFacing;
685 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
686
John Kessenich3dd1ce52019-10-17 07:08:40 -0600687 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
688 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
689 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
690 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
691 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
692 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
693
John Kessenicha28f7a72019-08-06 07:00:58 -0600694#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600695 // These *Distance capabilities logically belong here, but if the member is declared and
696 // then never used, consumers of SPIR-V prefer the capability not be declared.
697 // They are now generated when used, rather than here when declared.
698 // Potentially, the specification should be more clear what the minimum
699 // use needed is to trigger the capability.
700 //
John Kessenich92187592016-02-01 13:45:25 -0700701 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100702 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800703 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700704 return spv::BuiltInClipDistance;
705
706 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100707 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800708 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700709 return spv::BuiltInCullDistance;
710
711 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600712 builder.addCapability(spv::CapabilityMultiViewport);
713 if (glslangIntermediate->getStage() == EShLangVertex ||
714 glslangIntermediate->getStage() == EShLangTessControl ||
715 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800716
John Kessenich8317e6c2019-08-18 23:58:08 -0600717 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600718 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800719 }
John Kessenich92187592016-02-01 13:45:25 -0700720 return spv::BuiltInViewportIndex;
721
John Kessenich5e801132016-02-15 11:09:46 -0700722 case glslang::EbvSampleId:
723 builder.addCapability(spv::CapabilitySampleRateShading);
724 return spv::BuiltInSampleId;
725
726 case glslang::EbvSamplePosition:
727 builder.addCapability(spv::CapabilitySampleRateShading);
728 return spv::BuiltInSamplePosition;
729
730 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700731 return spv::BuiltInSampleMask;
732
John Kessenich78a45572016-07-08 14:05:15 -0600733 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700734 if (glslangIntermediate->getStage() == EShLangMeshNV) {
735 return spv::BuiltInLayer;
736 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600737 builder.addCapability(spv::CapabilityGeometry);
738 if (glslangIntermediate->getStage() == EShLangVertex ||
739 glslangIntermediate->getStage() == EShLangTessControl ||
740 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800741
John Kessenich8317e6c2019-08-18 23:58:08 -0600742 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600743 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800744 }
John Kessenich78a45572016-07-08 14:05:15 -0600745 return spv::BuiltInLayer;
746
John Kessenichda581a22015-10-14 14:10:30 -0600747 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600748 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800749 builder.addCapability(spv::CapabilityDrawParameters);
750 return spv::BuiltInBaseVertex;
751
John Kessenichda581a22015-10-14 14:10:30 -0600752 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600753 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800754 builder.addCapability(spv::CapabilityDrawParameters);
755 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200756
John Kessenichda581a22015-10-14 14:10:30 -0600757 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600758 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800759 builder.addCapability(spv::CapabilityDrawParameters);
760 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200761
762 case glslang::EbvPrimitiveId:
763 if (glslangIntermediate->getStage() == EShLangFragment)
764 builder.addCapability(spv::CapabilityGeometry);
765 return spv::BuiltInPrimitiveId;
766
Rex Xu37cdcee2017-06-29 17:46:34 +0800767 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800768 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
769 builder.addCapability(spv::CapabilityStencilExportEXT);
770 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800771
John Kessenich140f3df2015-06-26 16:58:36 -0600772 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600773 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
774 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
775 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
776 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600777 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800778
Rex Xu574ab042016-04-14 16:53:07 +0800779 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800780 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800781 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
782 return spv::BuiltInSubgroupSize;
783
Rex Xu574ab042016-04-14 16:53:07 +0800784 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800785 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800786 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
787 return spv::BuiltInSubgroupLocalInvocationId;
788
Rex Xu574ab042016-04-14 16:53:07 +0800789 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800790 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
791 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600792 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800793
Rex Xu574ab042016-04-14 16:53:07 +0800794 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800795 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
796 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600797 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800798
Rex Xu574ab042016-04-14 16:53:07 +0800799 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800800 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
801 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600802 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800803
Rex Xu574ab042016-04-14 16:53:07 +0800804 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800805 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
806 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600807 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800808
Rex Xu574ab042016-04-14 16:53:07 +0800809 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800810 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
811 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600812 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800813
John Kessenich66011cb2018-03-06 16:12:04 -0700814 case glslang::EbvNumSubgroups:
815 builder.addCapability(spv::CapabilityGroupNonUniform);
816 return spv::BuiltInNumSubgroups;
817
818 case glslang::EbvSubgroupID:
819 builder.addCapability(spv::CapabilityGroupNonUniform);
820 return spv::BuiltInSubgroupId;
821
822 case glslang::EbvSubgroupSize2:
823 builder.addCapability(spv::CapabilityGroupNonUniform);
824 return spv::BuiltInSubgroupSize;
825
826 case glslang::EbvSubgroupInvocation2:
827 builder.addCapability(spv::CapabilityGroupNonUniform);
828 return spv::BuiltInSubgroupLocalInvocationId;
829
830 case glslang::EbvSubgroupEqMask2:
831 builder.addCapability(spv::CapabilityGroupNonUniform);
832 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
833 return spv::BuiltInSubgroupEqMask;
834
835 case glslang::EbvSubgroupGeMask2:
836 builder.addCapability(spv::CapabilityGroupNonUniform);
837 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
838 return spv::BuiltInSubgroupGeMask;
839
840 case glslang::EbvSubgroupGtMask2:
841 builder.addCapability(spv::CapabilityGroupNonUniform);
842 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
843 return spv::BuiltInSubgroupGtMask;
844
845 case glslang::EbvSubgroupLeMask2:
846 builder.addCapability(spv::CapabilityGroupNonUniform);
847 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
848 return spv::BuiltInSubgroupLeMask;
849
850 case glslang::EbvSubgroupLtMask2:
851 builder.addCapability(spv::CapabilityGroupNonUniform);
852 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
853 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600854
Rex Xu17ff3432016-10-14 17:41:45 +0800855 case glslang::EbvBaryCoordNoPersp:
856 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
857 return spv::BuiltInBaryCoordNoPerspAMD;
858
859 case glslang::EbvBaryCoordNoPerspCentroid:
860 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
861 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
862
863 case glslang::EbvBaryCoordNoPerspSample:
864 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
865 return spv::BuiltInBaryCoordNoPerspSampleAMD;
866
867 case glslang::EbvBaryCoordSmooth:
868 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
869 return spv::BuiltInBaryCoordSmoothAMD;
870
871 case glslang::EbvBaryCoordSmoothCentroid:
872 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
873 return spv::BuiltInBaryCoordSmoothCentroidAMD;
874
875 case glslang::EbvBaryCoordSmoothSample:
876 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
877 return spv::BuiltInBaryCoordSmoothSampleAMD;
878
879 case glslang::EbvBaryCoordPullModel:
880 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
881 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800882
John Kessenich6c8aaac2017-02-27 01:20:51 -0700883 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600884 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700885 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700886 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700887
888 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600889 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700890 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700891 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700892
Daniel Koch5154db52018-11-26 10:01:58 -0500893 case glslang::EbvFragSizeEXT:
894 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
895 builder.addCapability(spv::CapabilityFragmentDensityEXT);
896 return spv::BuiltInFragSizeEXT;
897
898 case glslang::EbvFragInvocationCountEXT:
899 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
900 builder.addCapability(spv::CapabilityFragmentDensityEXT);
901 return spv::BuiltInFragInvocationCountEXT;
902
chaoc771d89f2017-01-13 01:10:53 -0800903 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800904 if (!memberDeclaration) {
905 builder.addExtension(spv::E_SPV_NV_viewport_array2);
906 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
907 }
chaoc771d89f2017-01-13 01:10:53 -0800908 return spv::BuiltInViewportMaskNV;
909 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800910 if (!memberDeclaration) {
911 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
912 builder.addCapability(spv::CapabilityShaderStereoViewNV);
913 }
chaoc771d89f2017-01-13 01:10:53 -0800914 return spv::BuiltInSecondaryPositionNV;
915 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800916 if (!memberDeclaration) {
917 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
918 builder.addCapability(spv::CapabilityShaderStereoViewNV);
919 }
chaoc771d89f2017-01-13 01:10:53 -0800920 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800921 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800922 if (!memberDeclaration) {
923 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
924 builder.addCapability(spv::CapabilityPerViewAttributesNV);
925 }
chaocdf3956c2017-02-14 14:52:34 -0800926 return spv::BuiltInPositionPerViewNV;
927 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800928 if (!memberDeclaration) {
929 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
930 builder.addCapability(spv::CapabilityPerViewAttributesNV);
931 }
chaocdf3956c2017-02-14 14:52:34 -0800932 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700933 case glslang::EbvFragFullyCoveredNV:
934 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
935 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
936 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700937 case glslang::EbvFragmentSizeNV:
938 builder.addExtension(spv::E_SPV_NV_shading_rate);
939 builder.addCapability(spv::CapabilityShadingRateNV);
940 return spv::BuiltInFragmentSizeNV;
941 case glslang::EbvInvocationsPerPixelNV:
942 builder.addExtension(spv::E_SPV_NV_shading_rate);
943 builder.addCapability(spv::CapabilityShadingRateNV);
944 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700945
Daniel Koch593a4e02019-05-27 16:46:31 -0400946 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400947 case glslang::EbvLaunchId:
948 return spv::BuiltInLaunchIdKHR;
949 case glslang::EbvLaunchSize:
950 return spv::BuiltInLaunchSizeKHR;
951 case glslang::EbvWorldRayOrigin:
952 return spv::BuiltInWorldRayOriginKHR;
953 case glslang::EbvWorldRayDirection:
954 return spv::BuiltInWorldRayDirectionKHR;
955 case glslang::EbvObjectRayOrigin:
956 return spv::BuiltInObjectRayOriginKHR;
957 case glslang::EbvObjectRayDirection:
958 return spv::BuiltInObjectRayDirectionKHR;
959 case glslang::EbvRayTmin:
960 return spv::BuiltInRayTminKHR;
961 case glslang::EbvRayTmax:
962 return spv::BuiltInRayTmaxKHR;
963 case glslang::EbvInstanceCustomIndex:
964 return spv::BuiltInInstanceCustomIndexKHR;
965 case glslang::EbvHitT:
966 return spv::BuiltInHitTKHR;
967 case glslang::EbvHitKind:
968 return spv::BuiltInHitKindKHR;
969 case glslang::EbvObjectToWorld:
970 case glslang::EbvObjectToWorld3x4:
971 return spv::BuiltInObjectToWorldKHR;
972 case glslang::EbvWorldToObject:
973 case glslang::EbvWorldToObject3x4:
974 return spv::BuiltInWorldToObjectKHR;
975 case glslang::EbvIncomingRayFlags:
976 return spv::BuiltInIncomingRayFlagsKHR;
977 case glslang::EbvGeometryIndex:
978 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400979
980 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700981 case glslang::EbvBaryCoordNV:
982 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
983 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
984 return spv::BuiltInBaryCoordNV;
985 case glslang::EbvBaryCoordNoPerspNV:
986 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
987 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
988 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400989
990 // mesh shaders
991 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700992 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400993 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700994 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400995 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700996 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400997 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700998 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001000 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001001 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001003 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001004 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001005 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001006 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001007
1008 // sm builtins
1009 case glslang::EbvWarpsPerSM:
1010 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1011 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1012 return spv::BuiltInWarpsPerSMNV;
1013 case glslang::EbvSMCount:
1014 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1015 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1016 return spv::BuiltInSMCountNV;
1017 case glslang::EbvWarpID:
1018 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1019 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1020 return spv::BuiltInWarpIDNV;
1021 case glslang::EbvSMID:
1022 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1023 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1024 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001025#endif
1026
Rex Xu3e783f92017-02-22 16:44:48 +08001027 default:
1028 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001029 }
1030}
1031
Rex Xufc618912015-09-09 16:42:49 +08001032// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001033spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001034{
1035 assert(type.getBasicType() == glslang::EbtSampler);
1036
John Kessenichb9197c82019-08-11 07:41:45 -06001037#ifdef GLSLANG_WEB
1038 return spv::ImageFormatUnknown;
1039#endif
1040
John Kessenich5d0fa972016-02-15 11:57:00 -07001041 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001042 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001043 case glslang::ElfRg32f:
1044 case glslang::ElfRg16f:
1045 case glslang::ElfR11fG11fB10f:
1046 case glslang::ElfR16f:
1047 case glslang::ElfRgba16:
1048 case glslang::ElfRgb10A2:
1049 case glslang::ElfRg16:
1050 case glslang::ElfRg8:
1051 case glslang::ElfR16:
1052 case glslang::ElfR8:
1053 case glslang::ElfRgba16Snorm:
1054 case glslang::ElfRg16Snorm:
1055 case glslang::ElfRg8Snorm:
1056 case glslang::ElfR16Snorm:
1057 case glslang::ElfR8Snorm:
1058
1059 case glslang::ElfRg32i:
1060 case glslang::ElfRg16i:
1061 case glslang::ElfRg8i:
1062 case glslang::ElfR16i:
1063 case glslang::ElfR8i:
1064
1065 case glslang::ElfRgb10a2ui:
1066 case glslang::ElfRg32ui:
1067 case glslang::ElfRg16ui:
1068 case glslang::ElfRg8ui:
1069 case glslang::ElfR16ui:
1070 case glslang::ElfR8ui:
1071 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1072 break;
1073
1074 default:
1075 break;
1076 }
1077
1078 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001079 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001080 case glslang::ElfNone: return spv::ImageFormatUnknown;
1081 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1082 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1083 case glslang::ElfR32f: return spv::ImageFormatR32f;
1084 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1085 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1086 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1087 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1088 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1089 case glslang::ElfR16f: return spv::ImageFormatR16f;
1090 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1091 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1092 case glslang::ElfRg16: return spv::ImageFormatRg16;
1093 case glslang::ElfRg8: return spv::ImageFormatRg8;
1094 case glslang::ElfR16: return spv::ImageFormatR16;
1095 case glslang::ElfR8: return spv::ImageFormatR8;
1096 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1097 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1098 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1099 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1100 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1101 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1102 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1103 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1104 case glslang::ElfR32i: return spv::ImageFormatR32i;
1105 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1106 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1107 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1108 case glslang::ElfR16i: return spv::ImageFormatR16i;
1109 case glslang::ElfR8i: return spv::ImageFormatR8i;
1110 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1111 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1112 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1113 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1114 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1115 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1116 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1117 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1118 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1119 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001120 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001121 }
1122}
1123
John Kessenich8985fc92020-03-03 10:25:07 -07001124spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1125 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001126{
John Kesseniche18fd202018-01-30 11:01:39 -07001127 if (selectionNode.getFlatten())
1128 return spv::SelectionControlFlattenMask;
1129 if (selectionNode.getDontFlatten())
1130 return spv::SelectionControlDontFlattenMask;
1131 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001132}
1133
John Kessenich8985fc92020-03-03 10:25:07 -07001134spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1135 const
steve-lunargf1709e72017-05-02 20:14:50 -06001136{
John Kesseniche18fd202018-01-30 11:01:39 -07001137 if (switchNode.getFlatten())
1138 return spv::SelectionControlFlattenMask;
1139 if (switchNode.getDontFlatten())
1140 return spv::SelectionControlDontFlattenMask;
1141 return spv::SelectionControlMaskNone;
1142}
1143
John Kessenicha2858d92018-01-31 08:11:18 -07001144// return a non-0 dependency if the dependency argument must be set
1145spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001146 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001147{
1148 spv::LoopControlMask control = spv::LoopControlMaskNone;
1149
1150 if (loopNode.getDontUnroll())
1151 control = control | spv::LoopControlDontUnrollMask;
1152 if (loopNode.getUnroll())
1153 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001154 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001155 control = control | spv::LoopControlDependencyInfiniteMask;
1156 else if (loopNode.getLoopDependency() > 0) {
1157 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001158 operands.push_back((unsigned int)loopNode.getLoopDependency());
1159 }
1160 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1161 if (loopNode.getMinIterations() > 0) {
1162 control = control | spv::LoopControlMinIterationsMask;
1163 operands.push_back(loopNode.getMinIterations());
1164 }
1165 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1166 control = control | spv::LoopControlMaxIterationsMask;
1167 operands.push_back(loopNode.getMaxIterations());
1168 }
1169 if (loopNode.getIterationMultiple() > 1) {
1170 control = control | spv::LoopControlIterationMultipleMask;
1171 operands.push_back(loopNode.getIterationMultiple());
1172 }
1173 if (loopNode.getPeelCount() > 0) {
1174 control = control | spv::LoopControlPeelCountMask;
1175 operands.push_back(loopNode.getPeelCount());
1176 }
1177 if (loopNode.getPartialCount() > 0) {
1178 control = control | spv::LoopControlPartialCountMask;
1179 operands.push_back(loopNode.getPartialCount());
1180 }
John Kessenicha2858d92018-01-31 08:11:18 -07001181 }
John Kesseniche18fd202018-01-30 11:01:39 -07001182
1183 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001184}
1185
John Kessenicha5c5fb62017-05-05 05:09:58 -06001186// Translate glslang type to SPIR-V storage class.
1187spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1188{
Torosdagli06c2eee2020-03-19 11:09:57 -04001189 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001190 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001191 if (type.getQualifier().isPipeInput())
1192 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001193 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001194 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001195
1196 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001197 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001198 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001199 return spv::StorageClassAtomicCounter;
1200 if (type.containsOpaque())
1201 return spv::StorageClassUniformConstant;
1202 }
1203
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001204 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001205 type.getQualifier().isShaderRecord()) {
1206 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001207 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001208
John Kessenichbed4e4f2017-09-08 02:38:07 -06001209 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001210 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001211 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001212 }
1213
1214 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001215 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001216 return spv::StorageClassPushConstant;
1217 if (type.getBasicType() == glslang::EbtBlock)
1218 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001219 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001220 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001221
1222 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001223 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1224 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1225 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001226 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001227#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001228 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1229 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1230 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1231 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1232 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001233#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001234 default:
1235 assert(0);
1236 break;
1237 }
1238
1239 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001240}
1241
John Kessenich5611c6d2018-04-05 11:25:02 -06001242// Add capabilities pertaining to how an array is indexed.
1243void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1244 const glslang::TType& indexType)
1245{
John Kessenichb9197c82019-08-11 07:41:45 -06001246#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001247 if (indexType.getQualifier().isNonUniform()) {
1248 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001249 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001250 if (baseType.getBasicType() == glslang::EbtSampler) {
1251 if (baseType.getQualifier().hasAttachment())
1252 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001253 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001254 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001255 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001256 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1257 else if (baseType.isImage())
1258 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1259 else if (baseType.isTexture())
1260 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1261 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1262 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1263 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1264 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1265 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1266 }
1267 } else {
1268 // assume a dynamically uniform index
1269 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001270 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001271 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001272 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001273 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001274 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001275 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001276 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001277 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001278 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001279 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001280 }
1281 }
John Kessenichb9197c82019-08-11 07:41:45 -06001282#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001283}
1284
qining25262b32016-05-06 17:25:16 -04001285// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001286// descriptor set.
1287bool IsDescriptorResource(const glslang::TType& type)
1288{
John Kessenichf7497e22016-03-08 21:36:22 -07001289 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001290 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001291 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001292 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001293 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001294
1295 // non block...
1296 // basically samplerXXX/subpass/sampler/texture are all included
1297 // if they are the global-scope-class, not the function parameter
1298 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001299 if (type.getBasicType() == glslang::EbtSampler ||
1300 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001301 return type.getQualifier().isUniformOrBuffer();
1302
1303 // None of the above.
1304 return false;
1305}
1306
John Kesseniche0b6cad2015-12-24 10:30:13 -07001307void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1308{
1309 if (child.layoutMatrix == glslang::ElmNone)
1310 child.layoutMatrix = parent.layoutMatrix;
1311
1312 if (parent.invariant)
1313 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001314 if (parent.flat)
1315 child.flat = true;
1316 if (parent.centroid)
1317 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001318#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001319 if (parent.nopersp)
1320 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001321 if (parent.explicitInterp)
1322 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001323 if (parent.perPrimitiveNV)
1324 child.perPrimitiveNV = true;
1325 if (parent.perViewNV)
1326 child.perViewNV = true;
1327 if (parent.perTaskNV)
1328 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001329 if (parent.patch)
1330 child.patch = true;
1331 if (parent.sample)
1332 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001333 if (parent.coherent)
1334 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001335 if (parent.devicecoherent)
1336 child.devicecoherent = true;
1337 if (parent.queuefamilycoherent)
1338 child.queuefamilycoherent = true;
1339 if (parent.workgroupcoherent)
1340 child.workgroupcoherent = true;
1341 if (parent.subgroupcoherent)
1342 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001343 if (parent.shadercallcoherent)
1344 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001345 if (parent.nonprivate)
1346 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001347 if (parent.volatil)
1348 child.volatil = true;
1349 if (parent.restrict)
1350 child.restrict = true;
1351 if (parent.readonly)
1352 child.readonly = true;
1353 if (parent.writeonly)
1354 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001355#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001356}
1357
John Kessenichf2b7f332016-09-01 17:05:23 -06001358bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001359{
John Kessenich7b9fa252016-01-21 18:56:57 -07001360 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001361 // - struct members might inherit from a struct declaration
1362 // (note that non-block structs don't explicitly inherit,
1363 // only implicitly, meaning no decoration involved)
1364 // - affect decorations on the struct members
1365 // (note smooth does not, and expecting something like volatile
1366 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001367 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001368 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001369}
1370
John Kessenich140f3df2015-06-26 16:58:36 -06001371//
1372// Implement the TGlslangToSpvTraverser class.
1373//
1374
John Kessenich8985fc92020-03-03 10:25:07 -07001375TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1376 const glslang::TIntermediate* glslangIntermediate,
1377 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1378 TIntermTraverser(true, false, true),
1379 options(options),
1380 shaderEntry(nullptr), currentFunction(nullptr),
1381 sequenceDepth(0), logger(buildLogger),
1382 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1383 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1384 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001385 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1386 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001387{
1388 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1389
1390 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001391 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1392 glslangIntermediate->getVersion());
1393
John Kessenich121853f2017-05-31 17:11:16 -06001394 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001395 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001396 builder.setSourceFile(glslangIntermediate->getSourceFile());
1397
1398 // Set the source shader's text. If for SPV version 1.0, include
1399 // a preamble in comments stating the OpModuleProcessed instructions.
1400 // Otherwise, emit those as actual instructions.
1401 std::string text;
1402 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1403 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001404 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001405 text.append("// OpModuleProcessed ");
1406 text.append(processes[p]);
1407 text.append("\n");
1408 } else
1409 builder.addModuleProcessed(processes[p]);
1410 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001411 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001412 text.append("#line 1\n");
1413 text.append(glslangIntermediate->getSourceText());
1414 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001415 // Pass name and text for all included files
1416 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1417 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1418 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001419 }
John Kessenich140f3df2015-06-26 16:58:36 -06001420 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001421
1422 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1423 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1424
1425 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1426 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001427 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001428 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001429 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001430 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001431 memoryModel = spv::MemoryModelVulkanKHR;
1432 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001433 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001434 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001435 builder.setMemoryModel(addressingModel, memoryModel);
1436
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001437 if (glslangIntermediate->usingVariablePointers()) {
1438 builder.addCapability(spv::CapabilityVariablePointers);
1439 }
1440
John Kessenicheee9d532016-09-19 18:09:30 -06001441 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1442 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001443
1444 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001445 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1446 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001447 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001448
1449 // Add the top-level modes for this shader.
1450
John Kessenich92187592016-02-01 13:45:25 -07001451 if (glslangIntermediate->getXfbMode()) {
1452 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001453 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001454 }
John Kessenich140f3df2015-06-26 16:58:36 -06001455
alelenv59216d52020-05-21 04:38:41 -07001456 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001457 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1458 }
1459
John Kessenich140f3df2015-06-26 16:58:36 -06001460 unsigned int mode;
1461 switch (glslangIntermediate->getStage()) {
1462 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001463 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001464 break;
1465
John Kessenicha28f7a72019-08-06 07:00:58 -06001466 case EShLangFragment:
1467 builder.addCapability(spv::CapabilityShader);
1468 if (glslangIntermediate->getPixelCenterInteger())
1469 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1470
1471 if (glslangIntermediate->getOriginUpperLeft())
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1473 else
1474 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1475
1476 if (glslangIntermediate->getEarlyFragmentTests())
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1478
1479 if (glslangIntermediate->getPostDepthCoverage()) {
1480 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1481 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1482 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1483 }
1484
John Kessenichb9197c82019-08-11 07:41:45 -06001485 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1486 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1487
1488#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001489
John Kessenicha28f7a72019-08-06 07:00:58 -06001490 switch(glslangIntermediate->getDepth()) {
1491 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1492 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1493 default: mode = spv::ExecutionModeMax; break;
1494 }
1495 if (mode != spv::ExecutionModeMax)
1496 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001497 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001498 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1499 break;
1500 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1501 break;
1502 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1503 break;
1504 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1505 break;
1506 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1507 break;
1508 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1509 break;
1510 default: mode = spv::ExecutionModeMax;
1511 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001512 }
1513 if (mode != spv::ExecutionModeMax) {
1514 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1515 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1516 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1517 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1518 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1519 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1520 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1521 } else {
1522 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1523 }
1524 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1525 }
John Kessenichb9197c82019-08-11 07:41:45 -06001526#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001527 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001528
John Kessenicha28f7a72019-08-06 07:00:58 -06001529 case EShLangCompute:
1530 builder.addCapability(spv::CapabilityShader);
1531 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1532 glslangIntermediate->getLocalSize(1),
1533 glslangIntermediate->getLocalSize(2));
1534 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1535 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1536 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1537 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1538 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1539 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1540 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1541 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1542 }
1543 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001544#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001545 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001546 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001547 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001548
steve-lunarge7412492017-03-23 11:56:07 -06001549 glslang::TLayoutGeometry primitive;
1550
1551 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001552 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1553 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001554 primitive = glslangIntermediate->getOutputPrimitive();
1555 } else {
1556 primitive = glslangIntermediate->getInputPrimitive();
1557 }
1558
1559 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001560 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1561 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1562 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001563 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001564 }
John Kessenich4016e382016-07-15 11:53:56 -06001565 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001566 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1567
John Kesseniche6903322015-10-13 16:29:02 -06001568 switch (glslangIntermediate->getVertexSpacing()) {
1569 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1570 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1571 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001572 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001573 }
John Kessenich4016e382016-07-15 11:53:56 -06001574 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001575 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1576
1577 switch (glslangIntermediate->getVertexOrder()) {
1578 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1579 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001580 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001581 }
John Kessenich4016e382016-07-15 11:53:56 -06001582 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001583 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1584
1585 if (glslangIntermediate->getPointMode())
1586 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001587 break;
1588
1589 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001590 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001591 switch (glslangIntermediate->getInputPrimitive()) {
1592 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1593 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1594 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001595 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001596 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001597 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001598 }
John Kessenich4016e382016-07-15 11:53:56 -06001599 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001600 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001601
John Kessenich140f3df2015-06-26 16:58:36 -06001602 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1603
1604 switch (glslangIntermediate->getOutputPrimitive()) {
1605 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1606 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1607 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001608 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001609 }
John Kessenich4016e382016-07-15 11:53:56 -06001610 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001611 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1612 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1613 break;
1614
Daniel Kochdb32b242020-03-17 20:42:47 -04001615 case EShLangRayGen:
1616 case EShLangIntersect:
1617 case EShLangAnyHit:
1618 case EShLangClosestHit:
1619 case EShLangMiss:
1620 case EShLangCallable:
1621 {
1622 auto& extensions = glslangIntermediate->getRequestedExtensions();
1623 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1624 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1625 builder.addExtension("SPV_KHR_ray_tracing");
1626 }
1627 else {
1628 builder.addCapability(spv::CapabilityRayTracingNV);
1629 builder.addExtension("SPV_NV_ray_tracing");
1630 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001631 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001632 }
Chao Chen3c366992018-09-19 11:41:59 -07001633 case EShLangTaskNV:
1634 case EShLangMeshNV:
1635 builder.addCapability(spv::CapabilityMeshShadingNV);
1636 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1637 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1638 glslangIntermediate->getLocalSize(1),
1639 glslangIntermediate->getLocalSize(2));
1640 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001641 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1642 glslangIntermediate->getVertices());
1643 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1644 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001645
1646 switch (glslangIntermediate->getOutputPrimitive()) {
1647 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1648 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1649 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1650 default: mode = spv::ExecutionModeMax; break;
1651 }
1652 if (mode != spv::ExecutionModeMax)
1653 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1654 }
1655 break;
1656#endif
1657
John Kessenich140f3df2015-06-26 16:58:36 -06001658 default:
1659 break;
1660 }
John Kessenich140f3df2015-06-26 16:58:36 -06001661}
1662
John Kessenichfca82622016-11-26 13:23:20 -07001663// Finish creating SPV, after the traversal is complete.
1664void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001665{
John Kessenichf04c51b2018-08-03 15:56:12 -06001666 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001667 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001668 builder.setBuildPoint(shaderEntry->getLastBlock());
1669 builder.leaveFunction();
1670 }
1671
John Kessenich7ba63412015-12-20 17:37:07 -07001672 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001673 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1674 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001675
David Neto8c3d5b42019-10-21 14:50:31 -04001676 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001677 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001678 // Note: WebGPU code generation must have the opportunity to aggressively
1679 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001680 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001681}
1682
John Kessenichfca82622016-11-26 13:23:20 -07001683// Write the SPV into 'out'.
1684void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001685{
John Kessenichfca82622016-11-26 13:23:20 -07001686 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001687}
1688
1689//
1690// Implement the traversal functions.
1691//
1692// Return true from interior nodes to have the external traversal
1693// continue on to children. Return false if children were
1694// already processed.
1695//
1696
1697//
qining25262b32016-05-06 17:25:16 -04001698// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001699// - uniform/input reads
1700// - output writes
1701// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1702// - something simple that degenerates into the last bullet
1703//
1704void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1705{
qining75d1d802016-04-06 14:42:01 -04001706 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001707 if (symbol->getType().isStruct())
1708 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1709
qining75d1d802016-04-06 14:42:01 -04001710 if (symbol->getType().getQualifier().isSpecConstant())
1711 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1712
John Kessenich140f3df2015-06-26 16:58:36 -06001713 // getSymbolId() will set up all the IO decorations on the first call.
1714 // Formal function parameters were mapped during makeFunctions().
1715 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001716
John Kessenich7ba63412015-12-20 17:37:07 -07001717 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001718 if (!symbol->getType().getQualifier().isParamInput() &&
1719 !symbol->getType().getQualifier().isParamOutput()) {
1720 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1721 // Consider adding to the OpEntryPoint interface list.
1722 // Only looking at structures if they have at least one member.
1723 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1724 spv::StorageClass sc = builder.getStorageClass(id);
1725 // Before SPIR-V 1.4, we only want to include Input and Output.
1726 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001727 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001728 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1729 iOSet.insert(id);
1730 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001731 }
John Kessenich5f77d862017-09-19 11:09:59 -06001732 }
John Kessenich9c14f772019-06-17 08:38:35 -06001733
Daniel Kochdb32b242020-03-17 20:42:47 -04001734 // If the SPIR-V type is required to be different than the AST type
1735 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001736 // translate now from the SPIR-V type to the AST type, for the consuming
1737 // operation.
1738 // Note this turns it from an l-value to an r-value.
1739 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1740 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1741 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001742 }
1743
1744 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001745 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001746 // Prepare to generate code for the access
1747
1748 // L-value chains will be computed left to right. We're on the symbol now,
1749 // which is the left-most part of the access chain, so now is "clear" time,
1750 // followed by setting the base.
1751 builder.clearAccessChain();
1752
1753 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001754 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001755 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001756 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001757 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001758 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001759 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001760 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001761 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1762 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001763 builder.setAccessChainRValue(id);
1764 else
1765 builder.setAccessChainLValue(id);
1766 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001767
John Kessenichb9197c82019-08-11 07:41:45 -06001768#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001769 // Process linkage-only nodes for any special additional interface work.
1770 if (linkageOnly) {
1771 if (glslangIntermediate->getHlslFunctionality1()) {
1772 // Map implicit counter buffers to their originating buffers, which should have been
1773 // seen by now, given earlier pruning of unused counters, and preservation of order
1774 // of declaration.
1775 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1776 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1777 // Save possible originating buffers for counter buffers, keyed by
1778 // making the potential counter-buffer name.
1779 std::string keyName = symbol->getName().c_str();
1780 keyName = glslangIntermediate->addCounterBufferName(keyName);
1781 counterOriginator[keyName] = symbol;
1782 } else {
1783 // Handle a counter buffer, by finding the saved originating buffer.
1784 std::string keyName = symbol->getName().c_str();
1785 auto it = counterOriginator.find(keyName);
1786 if (it != counterOriginator.end()) {
1787 id = getSymbolId(it->second);
1788 if (id != spv::NoResult) {
1789 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001790 if (counterId != spv::NoResult) {
1791 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001792 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001793 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001794 }
1795 }
1796 }
1797 }
1798 }
1799 }
John Kessenich155d3512019-08-08 23:29:20 -06001800#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001801}
1802
1803bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1804{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001805 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001806 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1807 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1808 }
1809 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1810 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1811 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001812
qining40887662016-04-03 22:20:42 -04001813 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1814 if (node->getType().getQualifier().isSpecConstant())
1815 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1816
John Kessenich140f3df2015-06-26 16:58:36 -06001817 // First, handle special cases
1818 switch (node->getOp()) {
1819 case glslang::EOpAssign:
1820 case glslang::EOpAddAssign:
1821 case glslang::EOpSubAssign:
1822 case glslang::EOpMulAssign:
1823 case glslang::EOpVectorTimesMatrixAssign:
1824 case glslang::EOpVectorTimesScalarAssign:
1825 case glslang::EOpMatrixTimesScalarAssign:
1826 case glslang::EOpMatrixTimesMatrixAssign:
1827 case glslang::EOpDivAssign:
1828 case glslang::EOpModAssign:
1829 case glslang::EOpAndAssign:
1830 case glslang::EOpInclusiveOrAssign:
1831 case glslang::EOpExclusiveOrAssign:
1832 case glslang::EOpLeftShiftAssign:
1833 case glslang::EOpRightShiftAssign:
1834 // A bin-op assign "a += b" means the same thing as "a = a + b"
1835 // where a is evaluated before b. For a simple assignment, GLSL
1836 // says to evaluate the left before the right. So, always, left
1837 // node then right node.
1838 {
1839 // get the left l-value, save it away
1840 builder.clearAccessChain();
1841 node->getLeft()->traverse(this);
1842 spv::Builder::AccessChain lValue = builder.getAccessChain();
1843
1844 // evaluate the right
1845 builder.clearAccessChain();
1846 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001847 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001848
1849 if (node->getOp() != glslang::EOpAssign) {
1850 // the left is also an r-value
1851 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001852 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001853
1854 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001855 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001856 TranslateNoContractionDecoration(node->getType().getQualifier()),
1857 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001858 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001859 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1860 node->getType().getBasicType());
1861
1862 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001863 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001864 }
1865
1866 // store the result
1867 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001868 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001869
1870 // assignments are expressions having an rValue after they are evaluated...
1871 builder.clearAccessChain();
1872 builder.setAccessChainRValue(rValue);
1873 }
1874 return false;
1875 case glslang::EOpIndexDirect:
1876 case glslang::EOpIndexDirectStruct:
1877 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001878 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001879 // Get the left part of the access chain.
1880 node->getLeft()->traverse(this);
1881
1882 // Add the next element in the chain
1883
David Netoa901ffe2016-06-08 14:11:40 +01001884 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001885 if (! node->getLeft()->getType().isArray() &&
1886 node->getLeft()->getType().isVector() &&
1887 node->getOp() == glslang::EOpIndexDirect) {
1888 // This is essentially a hard-coded vector swizzle of size 1,
1889 // so short circuit the access-chain stuff with a swizzle.
1890 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001891 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001892 int dummySize;
1893 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1894 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001895 glslangIntermediate->getBaseAlignmentScalar(
1896 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001897 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001898
1899 // Load through a block reference is performed with a dot operator that
1900 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1901 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001902 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001903 !node->getLeft()->getType().isArray() &&
1904 node->getOp() == glslang::EOpIndexDirectStruct)
1905 {
1906 spv::Id left = accessChainLoad(node->getLeft()->getType());
1907 builder.clearAccessChain();
1908 builder.setAccessChainLValue(left);
1909 }
1910
David Netoa901ffe2016-06-08 14:11:40 +01001911 int spvIndex = glslangIndex;
1912 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1913 node->getOp() == glslang::EOpIndexDirectStruct)
1914 {
1915 // This may be, e.g., an anonymous block-member selection, which generally need
1916 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001917 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1918 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1919 std::vector<int>& remapper = memberRemapper[glslangId];
1920 assert(remapper.size() > 0);
1921 spvIndex = remapper[glslangIndex];
1922 }
David Netoa901ffe2016-06-08 14:11:40 +01001923 }
John Kessenichebb50532016-05-16 19:22:05 -06001924
David Netoa901ffe2016-06-08 14:11:40 +01001925 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001926 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1927 TranslateCoherent(node->getLeft()->getType()),
1928 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001929
1930 // Add capabilities here for accessing PointSize and clip/cull distance.
1931 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001932 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001933 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001934 }
1935 }
1936 return false;
1937 case glslang::EOpIndexIndirect:
1938 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001939 // Array, matrix, or vector indirection with variable index.
1940 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001941 // matrices are arrays of vectors, so will also work for a matrix.
1942 // Will use the access chain's 'component' for variable index into a vector.
1943
1944 // This adapter is building access chains left to right.
1945 // Set up the access chain to the left.
1946 node->getLeft()->traverse(this);
1947
1948 // save it so that computing the right side doesn't trash it
1949 spv::Builder::AccessChain partial = builder.getAccessChain();
1950
1951 // compute the next index in the chain
1952 builder.clearAccessChain();
1953 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001954 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001955
John Kessenich5611c6d2018-04-05 11:25:02 -06001956 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1957
John Kessenich140f3df2015-06-26 16:58:36 -06001958 // restore the saved access chain
1959 builder.setAccessChain(partial);
1960
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001961 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1962 int dummySize;
1963 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1964 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001965 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1966 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001967 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001968 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1969 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001970 }
1971 return false;
1972 case glslang::EOpVectorSwizzle:
1973 {
1974 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001975 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001976 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001977 int dummySize;
1978 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1979 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001980 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1981 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001982 }
1983 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001984 case glslang::EOpMatrixSwizzle:
1985 logger->missingFunctionality("matrix swizzle");
1986 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001987 case glslang::EOpLogicalOr:
1988 case glslang::EOpLogicalAnd:
1989 {
1990
1991 // These may require short circuiting, but can sometimes be done as straight
1992 // binary operations. The right operand must be short circuited if it has
1993 // side effects, and should probably be if it is complex.
1994 if (isTrivial(node->getRight()->getAsTyped()))
1995 break; // handle below as a normal binary operation
1996 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001997 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1998 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001999 builder.clearAccessChain();
2000 builder.setAccessChainRValue(result);
2001 }
2002 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002003 default:
2004 break;
2005 }
2006
2007 // Assume generic binary op...
2008
John Kessenich32cfd492016-02-02 12:37:46 -07002009 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002010 builder.clearAccessChain();
2011 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002012 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002013
John Kessenich32cfd492016-02-02 12:37:46 -07002014 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002015 builder.clearAccessChain();
2016 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002017 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002018
John Kessenich32cfd492016-02-02 12:37:46 -07002019 // get result
John Kessenichead86222018-03-28 18:01:20 -06002020 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002021 TranslateNoContractionDecoration(node->getType().getQualifier()),
2022 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002023 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002024 convertGlslangToSpvType(node->getType()), left, right,
2025 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002026
John Kessenich50e57562015-12-21 21:21:11 -07002027 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002028 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002029 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002030 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002031 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002032 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002033 return false;
2034 }
John Kessenich140f3df2015-06-26 16:58:36 -06002035}
2036
John Kessenich9c14f772019-06-17 08:38:35 -06002037// Figure out what, if any, type changes are needed when accessing a specific built-in.
2038// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2039// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002040std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002041 const glslang::TType& glslangType)
2042{
Daniel Kochdb32b242020-03-17 20:42:47 -04002043 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002044 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002045 case glslang::EbvSubGroupEqMask:
2046 case glslang::EbvSubGroupGeMask:
2047 case glslang::EbvSubGroupGtMask:
2048 case glslang::EbvSubGroupLeMask:
2049 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002050 // these require changing a 64-bit scaler -> a vector of 32-bit components
2051 if (glslangType.isVector())
2052 break;
2053 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2054 builder.makeUintType(64));
2055 return ret;
2056 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002057 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2058 // builtins. During visitBinary we insert a transpose
2059 case glslang::EbvWorldToObject3x4:
2060 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002061 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2062 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2063 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002064 return ret;
2065 }
John Kessenich9c14f772019-06-17 08:38:35 -06002066 default:
2067 break;
2068 }
2069
2070 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2071 return ret;
2072}
2073
2074// For an object previously identified (see getForcedType() and forceType)
2075// as needing type translations, do the translation needed for a load, turning
2076// an L-value into in R-value.
2077spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2078{
2079 const auto forceIt = forceType.find(object);
2080 if (forceIt == forceType.end())
2081 return object;
2082
2083 spv::Id desiredTypeId = forceIt->second;
2084 spv::Id objectTypeId = builder.getTypeId(object);
2085 assert(builder.isPointerType(objectTypeId));
2086 objectTypeId = builder.getContainedTypeId(objectTypeId);
2087 if (builder.isVectorType(objectTypeId) &&
2088 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2089 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2090 // handle 32-bit v.xy* -> 64-bit
2091 builder.clearAccessChain();
2092 builder.setAccessChainLValue(object);
2093 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2094 std::vector<spv::Id> components;
2095 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2096 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2097
2098 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2099 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2100 builder.createCompositeConstruct(vecType, components));
2101 } else {
2102 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2103 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002104 } else if (builder.isMatrixType(objectTypeId)) {
2105 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2106 // and we insert a transpose after loading the original non-transposed builtins
2107 builder.clearAccessChain();
2108 builder.setAccessChainLValue(object);
2109 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2110 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2111
2112 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002113 logger->missingFunctionality("forcing non 32-bit vector type");
2114 }
2115
2116 return object;
2117}
2118
John Kessenich140f3df2015-06-26 16:58:36 -06002119bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2120{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002121 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002122
qining40887662016-04-03 22:20:42 -04002123 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2124 if (node->getType().getQualifier().isSpecConstant())
2125 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2126
John Kessenichfc51d282015-08-19 13:34:18 -06002127 spv::Id result = spv::NoResult;
2128
2129 // try texturing first
2130 result = createImageTextureFunctionCall(node);
2131 if (result != spv::NoResult) {
2132 builder.clearAccessChain();
2133 builder.setAccessChainRValue(result);
2134
2135 return false; // done with this node
2136 }
2137
2138 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002139
2140 if (node->getOp() == glslang::EOpArrayLength) {
2141 // Quite special; won't want to evaluate the operand.
2142
John Kessenich5611c6d2018-04-05 11:25:02 -06002143 // Currently, the front-end does not allow .length() on an array until it is sized,
2144 // except for the last block membeor of an SSBO.
2145 // TODO: If this changes, link-time sized arrays might show up here, and need their
2146 // size extracted.
2147
John Kessenichc9a80832015-09-12 12:17:44 -06002148 // Normal .length() would have been constant folded by the front-end.
2149 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002150 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002151
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002152 spv::Id length;
2153 if (node->getOperand()->getType().isCoopMat()) {
2154 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2155
2156 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2157 assert(builder.isCooperativeMatrixType(typeId));
2158
2159 length = builder.createCooperativeMatrixLength(typeId);
2160 } else {
2161 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2162 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002163 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2164 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002165 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2166 }
John Kessenichc9a80832015-09-12 12:17:44 -06002167
John Kessenich8c869672018-11-28 07:01:37 -07002168 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2169 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2170 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002171 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2172 if (builder.isInSpecConstCodeGenMode()) {
2173 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2174 } else {
2175 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2176 }
2177 }
John Kessenich8c869672018-11-28 07:01:37 -07002178
John Kessenichc9a80832015-09-12 12:17:44 -06002179 builder.clearAccessChain();
2180 builder.setAccessChainRValue(length);
2181
2182 return false;
2183 }
2184
John Kessenichfc51d282015-08-19 13:34:18 -06002185 // Start by evaluating the operand
2186
John Kessenich8c8505c2016-07-26 12:50:38 -06002187 // Does it need a swizzle inversion? If so, evaluation is inverted;
2188 // operate first on the swizzle base, then apply the swizzle.
2189 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002190 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2191 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002192 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2193 invertedType = getInvertedSwizzleType(*node->getOperand());
2194
John Kessenich140f3df2015-06-26 16:58:36 -06002195 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002196 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002197 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002198 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002199 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002200 operandNode = node->getOperand();
2201
2202 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002203
Rex Xufc618912015-09-09 16:42:49 +08002204 spv::Id operand = spv::NoResult;
2205
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002206 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2207
John Kessenichfb4f2332019-08-09 03:49:15 -06002208#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002209 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2210 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002211 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002212 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2213 node->getOp() == glslang::EOpRayQueryProceed ||
2214 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2215 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2216 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2217 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2218 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2219 node->getOp() == glslang::EOpRayQueryTerminate ||
2220 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002221 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002222 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2223 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2224 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002225#endif
2226 {
John Kessenich32cfd492016-02-02 12:37:46 -07002227 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002228 }
John Kessenich140f3df2015-06-26 16:58:36 -06002229
John Kessenichead86222018-03-28 18:01:20 -06002230 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002231 TranslateNoContractionDecoration(node->getType().getQualifier()),
2232 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002233
2234 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002235 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002236 result = createConversion(node->getOp(), decorations, resultType(), operand,
2237 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002238
2239 // if not, then possibly an operation
2240 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002241 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2242 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002243
2244 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002245 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002246 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002247 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002248 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002249
John Kessenich140f3df2015-06-26 16:58:36 -06002250 builder.clearAccessChain();
2251 builder.setAccessChainRValue(result);
2252
2253 return false; // done with this node
2254 }
2255
2256 // it must be a special case, check...
2257 switch (node->getOp()) {
2258 case glslang::EOpPostIncrement:
2259 case glslang::EOpPostDecrement:
2260 case glslang::EOpPreIncrement:
2261 case glslang::EOpPreDecrement:
2262 {
2263 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002264 spv::Id one = 0;
2265 if (node->getBasicType() == glslang::EbtFloat)
2266 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002267#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002268 else if (node->getBasicType() == glslang::EbtDouble)
2269 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002270 else if (node->getBasicType() == glslang::EbtFloat16)
2271 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002272 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2273 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002274 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2275 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002276 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2277 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002278#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002279 else
2280 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002281 glslang::TOperator op;
2282 if (node->getOp() == glslang::EOpPreIncrement ||
2283 node->getOp() == glslang::EOpPostIncrement)
2284 op = glslang::EOpAdd;
2285 else
2286 op = glslang::EOpSub;
2287
John Kessenichead86222018-03-28 18:01:20 -06002288 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002289 convertGlslangToSpvType(node->getType()), operand, one,
2290 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002291 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002292
2293 // The result of operation is always stored, but conditionally the
2294 // consumed result. The consumed result is always an r-value.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002295 builder.accessChainStore(result,
2296 TranslateNonUniformDecoration(node->getOperand()->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06002297 builder.clearAccessChain();
2298 if (node->getOp() == glslang::EOpPreIncrement ||
2299 node->getOp() == glslang::EOpPreDecrement)
2300 builder.setAccessChainRValue(result);
2301 else
2302 builder.setAccessChainRValue(operand);
2303 }
2304
2305 return false;
2306
John Kessenich155d3512019-08-08 23:29:20 -06002307#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002308 case glslang::EOpEmitStreamVertex:
2309 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2310 return false;
2311 case glslang::EOpEndStreamPrimitive:
2312 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2313 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002314 case glslang::EOpRayQueryTerminate:
2315 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2316 return false;
2317 case glslang::EOpRayQueryConfirmIntersection:
2318 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2319 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002320#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002321
2322 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002323 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002324 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002325 }
John Kessenich140f3df2015-06-26 16:58:36 -06002326}
2327
Jeff Bolz53134492019-06-25 13:31:10 -05002328// Construct a composite object, recursively copying members if their types don't match
2329spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2330{
2331 for (int c = 0; c < (int)constituents.size(); ++c) {
2332 spv::Id& constituent = constituents[c];
2333 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2334 spv::Id rType = builder.getTypeId(constituent);
2335 if (lType != rType) {
2336 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2337 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2338 } else if (builder.isStructType(rType)) {
2339 std::vector<spv::Id> rTypeConstituents;
2340 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2341 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002342 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2343 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002344 }
2345 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2346 } else {
2347 assert(builder.isArrayType(rType));
2348 std::vector<spv::Id> rTypeConstituents;
2349 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2350
2351 spv::Id elementRType = builder.getContainedTypeId(rType);
2352 for (int i = 0; i < numrTypeConstituents; ++i) {
2353 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2354 }
2355 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2356 }
2357 }
2358 }
2359 return builder.createCompositeConstruct(resultTypeId, constituents);
2360}
2361
John Kessenich140f3df2015-06-26 16:58:36 -06002362bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2363{
qining27e04a02016-04-14 16:40:20 -04002364 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2365 if (node->getType().getQualifier().isSpecConstant())
2366 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2367
John Kessenichfc51d282015-08-19 13:34:18 -06002368 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002369 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2370 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2371 // SPIR-V, for an out parameter
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002372 std::vector<glslang::TQualifier> complexLValueQualifiers;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002373 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002374
John Kessenich8985fc92020-03-03 10:25:07 -07002375 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2376 invertedType :
2377 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002378
2379 // try texturing
2380 result = createImageTextureFunctionCall(node);
2381 if (result != spv::NoResult) {
2382 builder.clearAccessChain();
2383 builder.setAccessChainRValue(result);
2384
2385 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002386 }
2387#ifndef GLSLANG_WEB
2388 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002389 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002390 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002391 // "imageStore" is a special case, which has no result
2392 return false;
2393 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002394#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002395
John Kessenich140f3df2015-06-26 16:58:36 -06002396 glslang::TOperator binOp = glslang::EOpNull;
2397 bool reduceComparison = true;
2398 bool isMatrix = false;
2399 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002400 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002401
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002402 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2403
John Kessenich140f3df2015-06-26 16:58:36 -06002404 assert(node->getOp());
2405
John Kessenichf6640762016-08-01 19:44:00 -06002406 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002407
2408 switch (node->getOp()) {
2409 case glslang::EOpSequence:
2410 {
2411 if (preVisit)
2412 ++sequenceDepth;
2413 else
2414 --sequenceDepth;
2415
2416 if (sequenceDepth == 1) {
2417 // If this is the parent node of all the functions, we want to see them
2418 // early, so all call points have actual SPIR-V functions to reference.
2419 // In all cases, still let the traverser visit the children for us.
2420 makeFunctions(node->getAsAggregate()->getSequence());
2421
John Kessenich6fccb3c2016-09-19 16:01:41 -06002422 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002423 // anything else gets there, so visit out of order, doing them all now.
2424 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2425
John Kessenich6a60c2f2016-12-08 21:01:59 -07002426 // 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 -06002427 // so do them manually.
2428 visitFunctions(node->getAsAggregate()->getSequence());
2429
2430 return false;
2431 }
2432
2433 return true;
2434 }
2435 case glslang::EOpLinkerObjects:
2436 {
2437 if (visit == glslang::EvPreVisit)
2438 linkageOnly = true;
2439 else
2440 linkageOnly = false;
2441
2442 return true;
2443 }
2444 case glslang::EOpComma:
2445 {
2446 // processing from left to right naturally leaves the right-most
2447 // lying around in the access chain
2448 glslang::TIntermSequence& glslangOperands = node->getSequence();
2449 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2450 glslangOperands[i]->traverse(this);
2451
2452 return false;
2453 }
2454 case glslang::EOpFunction:
2455 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002456 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002457 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002458 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002459 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002460 } else {
2461 handleFunctionEntry(node);
2462 }
2463 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002464 if (inEntryPoint)
2465 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002466 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002467 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002468 }
2469
2470 return true;
2471 case glslang::EOpParameters:
2472 // Parameters will have been consumed by EOpFunction processing, but not
2473 // the body, so we still visited the function node's children, making this
2474 // child redundant.
2475 return false;
2476 case glslang::EOpFunctionCall:
2477 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002478 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002479 if (node->isUserDefined())
2480 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002481 if (result) {
2482 builder.clearAccessChain();
2483 builder.setAccessChainRValue(result);
2484 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002485 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002486
2487 return false;
2488 }
2489 case glslang::EOpConstructMat2x2:
2490 case glslang::EOpConstructMat2x3:
2491 case glslang::EOpConstructMat2x4:
2492 case glslang::EOpConstructMat3x2:
2493 case glslang::EOpConstructMat3x3:
2494 case glslang::EOpConstructMat3x4:
2495 case glslang::EOpConstructMat4x2:
2496 case glslang::EOpConstructMat4x3:
2497 case glslang::EOpConstructMat4x4:
2498 case glslang::EOpConstructDMat2x2:
2499 case glslang::EOpConstructDMat2x3:
2500 case glslang::EOpConstructDMat2x4:
2501 case glslang::EOpConstructDMat3x2:
2502 case glslang::EOpConstructDMat3x3:
2503 case glslang::EOpConstructDMat3x4:
2504 case glslang::EOpConstructDMat4x2:
2505 case glslang::EOpConstructDMat4x3:
2506 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002507 case glslang::EOpConstructIMat2x2:
2508 case glslang::EOpConstructIMat2x3:
2509 case glslang::EOpConstructIMat2x4:
2510 case glslang::EOpConstructIMat3x2:
2511 case glslang::EOpConstructIMat3x3:
2512 case glslang::EOpConstructIMat3x4:
2513 case glslang::EOpConstructIMat4x2:
2514 case glslang::EOpConstructIMat4x3:
2515 case glslang::EOpConstructIMat4x4:
2516 case glslang::EOpConstructUMat2x2:
2517 case glslang::EOpConstructUMat2x3:
2518 case glslang::EOpConstructUMat2x4:
2519 case glslang::EOpConstructUMat3x2:
2520 case glslang::EOpConstructUMat3x3:
2521 case glslang::EOpConstructUMat3x4:
2522 case glslang::EOpConstructUMat4x2:
2523 case glslang::EOpConstructUMat4x3:
2524 case glslang::EOpConstructUMat4x4:
2525 case glslang::EOpConstructBMat2x2:
2526 case glslang::EOpConstructBMat2x3:
2527 case glslang::EOpConstructBMat2x4:
2528 case glslang::EOpConstructBMat3x2:
2529 case glslang::EOpConstructBMat3x3:
2530 case glslang::EOpConstructBMat3x4:
2531 case glslang::EOpConstructBMat4x2:
2532 case glslang::EOpConstructBMat4x3:
2533 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002534 case glslang::EOpConstructF16Mat2x2:
2535 case glslang::EOpConstructF16Mat2x3:
2536 case glslang::EOpConstructF16Mat2x4:
2537 case glslang::EOpConstructF16Mat3x2:
2538 case glslang::EOpConstructF16Mat3x3:
2539 case glslang::EOpConstructF16Mat3x4:
2540 case glslang::EOpConstructF16Mat4x2:
2541 case glslang::EOpConstructF16Mat4x3:
2542 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002543 isMatrix = true;
2544 // fall through
2545 case glslang::EOpConstructFloat:
2546 case glslang::EOpConstructVec2:
2547 case glslang::EOpConstructVec3:
2548 case glslang::EOpConstructVec4:
2549 case glslang::EOpConstructDouble:
2550 case glslang::EOpConstructDVec2:
2551 case glslang::EOpConstructDVec3:
2552 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002553 case glslang::EOpConstructFloat16:
2554 case glslang::EOpConstructF16Vec2:
2555 case glslang::EOpConstructF16Vec3:
2556 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002557 case glslang::EOpConstructBool:
2558 case glslang::EOpConstructBVec2:
2559 case glslang::EOpConstructBVec3:
2560 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002561 case glslang::EOpConstructInt8:
2562 case glslang::EOpConstructI8Vec2:
2563 case glslang::EOpConstructI8Vec3:
2564 case glslang::EOpConstructI8Vec4:
2565 case glslang::EOpConstructUint8:
2566 case glslang::EOpConstructU8Vec2:
2567 case glslang::EOpConstructU8Vec3:
2568 case glslang::EOpConstructU8Vec4:
2569 case glslang::EOpConstructInt16:
2570 case glslang::EOpConstructI16Vec2:
2571 case glslang::EOpConstructI16Vec3:
2572 case glslang::EOpConstructI16Vec4:
2573 case glslang::EOpConstructUint16:
2574 case glslang::EOpConstructU16Vec2:
2575 case glslang::EOpConstructU16Vec3:
2576 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002577 case glslang::EOpConstructInt:
2578 case glslang::EOpConstructIVec2:
2579 case glslang::EOpConstructIVec3:
2580 case glslang::EOpConstructIVec4:
2581 case glslang::EOpConstructUint:
2582 case glslang::EOpConstructUVec2:
2583 case glslang::EOpConstructUVec3:
2584 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002585 case glslang::EOpConstructInt64:
2586 case glslang::EOpConstructI64Vec2:
2587 case glslang::EOpConstructI64Vec3:
2588 case glslang::EOpConstructI64Vec4:
2589 case glslang::EOpConstructUint64:
2590 case glslang::EOpConstructU64Vec2:
2591 case glslang::EOpConstructU64Vec3:
2592 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002593 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002594 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002595 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002596 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002597 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002598 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002599 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002600 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002601 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002602 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002603 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002604 else if (node->getOp() == glslang::EOpConstructStruct ||
2605 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2606 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002607 std::vector<spv::Id> constituents;
2608 for (int c = 0; c < (int)arguments.size(); ++c)
2609 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002610 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002611 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002612 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002613 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002614 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002615
Bas Nieuwenhuizenc9ffeec2020-09-03 03:09:39 +02002616 if (node->getType().getQualifier().isNonUniform()) {
2617 builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
2618 }
2619
John Kessenich140f3df2015-06-26 16:58:36 -06002620 builder.clearAccessChain();
2621 builder.setAccessChainRValue(constructed);
2622
2623 return false;
2624 }
2625
2626 // These six are component-wise compares with component-wise results.
2627 // Forward on to createBinaryOperation(), requesting a vector result.
2628 case glslang::EOpLessThan:
2629 case glslang::EOpGreaterThan:
2630 case glslang::EOpLessThanEqual:
2631 case glslang::EOpGreaterThanEqual:
2632 case glslang::EOpVectorEqual:
2633 case glslang::EOpVectorNotEqual:
2634 {
2635 // Map the operation to a binary
2636 binOp = node->getOp();
2637 reduceComparison = false;
2638 switch (node->getOp()) {
2639 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2640 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2641 default: binOp = node->getOp(); break;
2642 }
2643
2644 break;
2645 }
2646 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002647 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002648 binOp = glslang::EOpMul;
2649 break;
2650 case glslang::EOpOuterProduct:
2651 // two vectors multiplied to make a matrix
2652 binOp = glslang::EOpOuterProduct;
2653 break;
2654 case glslang::EOpDot:
2655 {
qining25262b32016-05-06 17:25:16 -04002656 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002657 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002658 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002659 binOp = glslang::EOpMul;
2660 break;
2661 }
2662 case glslang::EOpMod:
2663 // when an aggregate, this is the floating-point mod built-in function,
2664 // which can be emitted by the one in createBinaryOperation()
2665 binOp = glslang::EOpMod;
2666 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002667
John Kessenich140f3df2015-06-26 16:58:36 -06002668 case glslang::EOpEmitVertex:
2669 case glslang::EOpEndPrimitive:
2670 case glslang::EOpBarrier:
2671 case glslang::EOpMemoryBarrier:
2672 case glslang::EOpMemoryBarrierAtomicCounter:
2673 case glslang::EOpMemoryBarrierBuffer:
2674 case glslang::EOpMemoryBarrierImage:
2675 case glslang::EOpMemoryBarrierShared:
2676 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002677 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002678 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002679 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002680 case glslang::EOpWorkgroupMemoryBarrier:
2681 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002682 case glslang::EOpSubgroupBarrier:
2683 case glslang::EOpSubgroupMemoryBarrier:
2684 case glslang::EOpSubgroupMemoryBarrierBuffer:
2685 case glslang::EOpSubgroupMemoryBarrierImage:
2686 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002687 noReturnValue = true;
2688 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2689 break;
2690
John Kessenich426394d2015-07-23 10:22:48 -06002691 case glslang::EOpAtomicAdd:
2692 case glslang::EOpAtomicMin:
2693 case glslang::EOpAtomicMax:
2694 case glslang::EOpAtomicAnd:
2695 case glslang::EOpAtomicOr:
2696 case glslang::EOpAtomicXor:
2697 case glslang::EOpAtomicExchange:
2698 case glslang::EOpAtomicCompSwap:
2699 atomic = true;
2700 break;
2701
John Kesseniche5eee8f2019-10-18 01:03:11 -06002702#ifndef GLSLANG_WEB
2703 case glslang::EOpAtomicStore:
2704 noReturnValue = true;
2705 // fallthrough
2706 case glslang::EOpAtomicLoad:
2707 atomic = true;
2708 break;
2709
John Kessenich0d0c6d32017-07-23 16:08:26 -06002710 case glslang::EOpAtomicCounterAdd:
2711 case glslang::EOpAtomicCounterSubtract:
2712 case glslang::EOpAtomicCounterMin:
2713 case glslang::EOpAtomicCounterMax:
2714 case glslang::EOpAtomicCounterAnd:
2715 case glslang::EOpAtomicCounterOr:
2716 case glslang::EOpAtomicCounterXor:
2717 case glslang::EOpAtomicCounterExchange:
2718 case glslang::EOpAtomicCounterCompSwap:
2719 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2720 builder.addCapability(spv::CapabilityAtomicStorageOps);
2721 atomic = true;
2722 break;
2723
Ian Romanickb3bd4022019-01-21 08:57:25 -08002724 case glslang::EOpAbsDifference:
2725 case glslang::EOpAddSaturate:
2726 case glslang::EOpSubSaturate:
2727 case glslang::EOpAverage:
2728 case glslang::EOpAverageRounded:
2729 case glslang::EOpMul32x16:
2730 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2731 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2732 binOp = node->getOp();
2733 break;
2734
Daniel Kochdb32b242020-03-17 20:42:47 -04002735 case glslang::EOpIgnoreIntersection:
2736 case glslang::EOpTerminateRay:
2737 case glslang::EOpTrace:
2738 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002739 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2740 noReturnValue = true;
2741 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002742 case glslang::EOpRayQueryInitialize:
2743 case glslang::EOpRayQueryTerminate:
2744 case glslang::EOpRayQueryGenerateIntersection:
2745 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002746 builder.addExtension("SPV_KHR_ray_query");
2747 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002748 noReturnValue = true;
2749 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002750 case glslang::EOpRayQueryProceed:
2751 case glslang::EOpRayQueryGetIntersectionType:
2752 case glslang::EOpRayQueryGetRayTMin:
2753 case glslang::EOpRayQueryGetRayFlags:
2754 case glslang::EOpRayQueryGetIntersectionT:
2755 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2756 case glslang::EOpRayQueryGetIntersectionInstanceId:
2757 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2758 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2759 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2760 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2761 case glslang::EOpRayQueryGetIntersectionFrontFace:
2762 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2763 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2764 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2765 case glslang::EOpRayQueryGetWorldRayDirection:
2766 case glslang::EOpRayQueryGetWorldRayOrigin:
2767 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2768 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2769 builder.addExtension("SPV_KHR_ray_query");
2770 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2771 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002772 case glslang::EOpCooperativeMatrixLoad:
2773 case glslang::EOpCooperativeMatrixStore:
2774 noReturnValue = true;
2775 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002776 case glslang::EOpBeginInvocationInterlock:
2777 case glslang::EOpEndInvocationInterlock:
2778 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2779 noReturnValue = true;
2780 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002781#endif
Chao Chen3c366992018-09-19 11:41:59 -07002782
Jeff Bolz04d73732019-05-31 13:06:01 -05002783 case glslang::EOpDebugPrintf:
2784 noReturnValue = true;
2785 break;
2786
John Kessenich140f3df2015-06-26 16:58:36 -06002787 default:
2788 break;
2789 }
2790
2791 //
2792 // See if it maps to a regular operation.
2793 //
John Kessenich140f3df2015-06-26 16:58:36 -06002794 if (binOp != glslang::EOpNull) {
2795 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2796 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2797 assert(left && right);
2798
2799 builder.clearAccessChain();
2800 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002801 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002802
2803 builder.clearAccessChain();
2804 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002805 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002806
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002807 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002808 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002809 TranslateNoContractionDecoration(node->getType().getQualifier()),
2810 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002811 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002812 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002813 left->getType().getBasicType(), reduceComparison);
2814
2815 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002816 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002817 builder.clearAccessChain();
2818 builder.setAccessChainRValue(result);
2819
2820 return false;
2821 }
2822
John Kessenich426394d2015-07-23 10:22:48 -06002823 //
2824 // Create the list of operands.
2825 //
John Kessenich140f3df2015-06-26 16:58:36 -06002826 glslang::TIntermSequence& glslangOperands = node->getSequence();
2827 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002828 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002829 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002830 // special case l-value operands; there are just a few
2831 bool lvalue = false;
2832 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002833 case glslang::EOpModf:
2834 if (arg == 1)
2835 lvalue = true;
2836 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002837
Torosdagli06c2eee2020-03-19 11:09:57 -04002838 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002839 case glslang::EOpRayQueryTerminate:
2840 case glslang::EOpRayQueryConfirmIntersection:
2841 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002842 case glslang::EOpRayQueryGenerateIntersection:
2843 case glslang::EOpRayQueryGetIntersectionType:
2844 case glslang::EOpRayQueryGetIntersectionT:
2845 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2846 case glslang::EOpRayQueryGetIntersectionInstanceId:
2847 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2848 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2849 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2850 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2851 case glslang::EOpRayQueryGetIntersectionFrontFace:
2852 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2853 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2854 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2855 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2856 if (arg == 0)
2857 lvalue = true;
2858 break;
2859
John Kesseniche5eee8f2019-10-18 01:03:11 -06002860 case glslang::EOpAtomicAdd:
2861 case glslang::EOpAtomicMin:
2862 case glslang::EOpAtomicMax:
2863 case glslang::EOpAtomicAnd:
2864 case glslang::EOpAtomicOr:
2865 case glslang::EOpAtomicXor:
2866 case glslang::EOpAtomicExchange:
2867 case glslang::EOpAtomicCompSwap:
2868 if (arg == 0)
2869 lvalue = true;
2870 break;
2871
John Kessenicha28f7a72019-08-06 07:00:58 -06002872#ifndef GLSLANG_WEB
2873 case glslang::EOpFrexp:
2874 if (arg == 1)
2875 lvalue = true;
2876 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002877 case glslang::EOpInterpolateAtSample:
2878 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002879 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002880 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002881 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002882
2883 // Does it need a swizzle inversion? If so, evaluation is inverted;
2884 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002885 // That is, we transform
2886 //
2887 // interpolate(v.zy) -> interpolate(v).zy
2888 //
John Kessenichecba76f2017-01-06 00:34:48 -07002889 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002890 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002891 invertedType = convertGlslangToSpvType(
2892 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002893 }
Rex Xu7a26c172015-12-08 17:12:09 +08002894 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002895 case glslang::EOpAtomicLoad:
2896 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002897 case glslang::EOpAtomicCounterAdd:
2898 case glslang::EOpAtomicCounterSubtract:
2899 case glslang::EOpAtomicCounterMin:
2900 case glslang::EOpAtomicCounterMax:
2901 case glslang::EOpAtomicCounterAnd:
2902 case glslang::EOpAtomicCounterOr:
2903 case glslang::EOpAtomicCounterXor:
2904 case glslang::EOpAtomicCounterExchange:
2905 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002906 if (arg == 0)
2907 lvalue = true;
2908 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002909 case glslang::EOpAddCarry:
2910 case glslang::EOpSubBorrow:
2911 if (arg == 2)
2912 lvalue = true;
2913 break;
2914 case glslang::EOpUMulExtended:
2915 case glslang::EOpIMulExtended:
2916 if (arg >= 2)
2917 lvalue = true;
2918 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002919 case glslang::EOpCooperativeMatrixLoad:
2920 if (arg == 0 || arg == 1)
2921 lvalue = true;
2922 break;
2923 case glslang::EOpCooperativeMatrixStore:
2924 if (arg == 1)
2925 lvalue = true;
2926 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002927#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002928 default:
2929 break;
2930 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002931 builder.clearAccessChain();
2932 if (invertedType != spv::NoType && arg == 0)
2933 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2934 else
2935 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002936
John Kessenichb9197c82019-08-11 07:41:45 -06002937#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002938 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2939 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2940
2941 if (arg == 1) {
2942 // fold "element" parameter into the access chain
2943 spv::Builder::AccessChain save = builder.getAccessChain();
2944 builder.clearAccessChain();
2945 glslangOperands[2]->traverse(this);
2946
2947 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2948
2949 builder.setAccessChain(save);
2950
2951 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002952 builder.accessChainPush(elementId,
2953 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2954 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002955
2956 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2957 unsigned int alignment = builder.getAccessChain().alignment;
2958
2959 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2960 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2961 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2962 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2963 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002964 if (builder.getStorageClass(builder.getAccessChain().base) ==
2965 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002966 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2967 }
2968
2969 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2970
2971 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2972 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2973 }
2974
John Kessenich8985fc92020-03-03 10:25:07 -07002975 if (memoryAccess &
2976 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2977 memoryAccessOperands.push_back(spv::IdImmediate(true,
2978 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002979 }
2980 } else if (arg == 2) {
2981 continue;
2982 }
2983 }
John Kessenichb9197c82019-08-11 07:41:45 -06002984#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002985
John Kessenichbbbd9a22020-03-03 07:21:37 -07002986 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002987 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002988 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2989 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2990 // reduce to a simple access chain. So, we need a temporary vector to
2991 // receive the result, and must later swizzle that into the original
2992 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06002993 complexLvalues.push_back(builder.getAccessChain());
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002994 complexLValueQualifiers.push_back(glslangOperands[arg]->getAsTyped()->getType().getQualifier());
John Kessenich435dd802020-06-30 01:27:08 -06002995 temporaryLvalues.push_back(builder.createVariable(
2996 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06002997 builder.accessChainGetInferredType(), "swizzleTemp"));
2998 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07002999 } else {
3000 operands.push_back(builder.accessChainGetLValue());
3001 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003002 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3003 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3004 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003005 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003006 glslang::TOperator glslangOp = node->getOp();
3007 if (arg == 1 &&
3008 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3009 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3010 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3011 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3012 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3013 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3014 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3015 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3016 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3017 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3018 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3019 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3020 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3021 )) {
3022 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3023 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3024 }
3025 else {
3026 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3027 }
3028
John Kesseniche485c7a2017-05-31 18:50:53 -06003029 }
John Kessenich140f3df2015-06-26 16:58:36 -06003030 }
John Kessenich426394d2015-07-23 10:22:48 -06003031
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003032 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003033#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003034 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3035 std::vector<spv::IdImmediate> idImmOps;
3036
3037 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3038 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3039 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3040 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3041 // get the pointee type
3042 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3043 assert(builder.isCooperativeMatrixType(typeId));
3044 // do the op
3045 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3046 // store the result to the pointer (out param 'm')
3047 builder.createStore(result, operands[0]);
3048 result = 0;
3049 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3050 std::vector<spv::IdImmediate> idImmOps;
3051
3052 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3053 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3054 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3055 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3056 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3057
3058 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3059 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003060 } else
3061#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003062 if (atomic) {
3063 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003064 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3065 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003066 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3067 if (!nonSemanticDebugPrintf) {
3068 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3069 }
3070 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3071 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003072 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003073 // Pass through to generic operations.
3074 switch (glslangOperands.size()) {
3075 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003076 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003077 break;
3078 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003079 {
3080 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003081 TranslateNoContractionDecoration(node->getType().getQualifier()),
3082 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003083 result = createUnaryOperation(
3084 node->getOp(), decorations,
3085 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003086 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003087 }
John Kessenich426394d2015-07-23 10:22:48 -06003088 break;
3089 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003090 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003091 break;
3092 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003093
John Kessenichbbbd9a22020-03-03 07:21:37 -07003094 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003095 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003096
3097 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3098 builder.setAccessChain(complexLvalues[i]);
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003099 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision), TranslateNonUniformDecoration(complexLValueQualifiers[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003100 }
John Kessenich140f3df2015-06-26 16:58:36 -06003101 }
3102
3103 if (noReturnValue)
3104 return false;
3105
3106 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003107 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003108 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003109 } else {
3110 builder.clearAccessChain();
3111 builder.setAccessChainRValue(result);
3112 return false;
3113 }
3114}
3115
John Kessenich433e9ff2017-01-26 20:31:11 -07003116// This path handles both if-then-else and ?:
3117// The if-then-else has a node type of void, while
3118// ?: has either a void or a non-void node type
3119//
3120// Leaving the result, when not void:
3121// GLSL only has r-values as the result of a :?, but
3122// if we have an l-value, that can be more efficient if it will
3123// become the base of a complex r-value expression, because the
3124// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003125bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3126{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003127 // see if OpSelect can handle it
3128 const auto isOpSelectable = [&]() {
3129 if (node->getBasicType() == glslang::EbtVoid)
3130 return false;
3131 // OpSelect can do all other types starting with SPV 1.4
3132 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3133 // pre-1.4, only scalars and vectors can be handled
3134 if ((!node->getType().isScalar() && !node->getType().isVector()))
3135 return false;
3136 }
3137 return true;
3138 };
3139
John Kessenich4bee5312018-02-20 21:29:05 -07003140 // See if it simple and safe, or required, to execute both sides.
3141 // Crucially, side effects must be either semantically required or avoided,
3142 // and there are performance trade-offs.
3143 // Return true if required or a good idea (and safe) to execute both sides,
3144 // false otherwise.
3145 const auto bothSidesPolicy = [&]() -> bool {
3146 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003147 if (node->getTrueBlock() == nullptr ||
3148 node->getFalseBlock() == nullptr)
3149 return false;
3150
John Kessenich4bee5312018-02-20 21:29:05 -07003151 // required? (unless we write additional code to look for side effects
3152 // and make performance trade-offs if none are present)
3153 if (!node->getShortCircuit())
3154 return true;
3155
3156 // if not required to execute both, decide based on performance/practicality...
3157
John Kessenich0c1e71a2019-01-10 18:23:06 +07003158 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003159 return false;
3160
John Kessenich433e9ff2017-01-26 20:31:11 -07003161 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3162 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3163
3164 // return true if a single operand to ? : is okay for OpSelect
3165 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003166 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003167 };
3168
3169 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3170 operandOkay(node->getFalseBlock()->getAsTyped());
3171 };
3172
John Kessenich4bee5312018-02-20 21:29:05 -07003173 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3174 // emit the condition before doing anything with selection
3175 node->getCondition()->traverse(this);
3176 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3177
3178 // Find a way of executing both sides and selecting the right result.
3179 const auto executeBothSides = [&]() -> void {
3180 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003181 node->getTrueBlock()->traverse(this);
3182 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3183 node->getFalseBlock()->traverse(this);
3184 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3185
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003186 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003187
John Kessenich4bee5312018-02-20 21:29:05 -07003188 // done if void
3189 if (node->getBasicType() == glslang::EbtVoid)
3190 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003191
John Kessenich4bee5312018-02-20 21:29:05 -07003192 // emit code to select between trueValue and falseValue
3193
3194 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003195 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003196 // Emit OpSelect for this selection.
3197
3198 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003199 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3200 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003201 condition = builder.smearScalar(spv::NoPrecision, condition,
3202 builder.makeVectorType(builder.makeBoolType(),
3203 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003204 }
John Kessenich4bee5312018-02-20 21:29:05 -07003205
3206 // OpSelect
3207 result = builder.createTriOp(spv::OpSelect,
3208 convertGlslangToSpvType(node->getType()), condition,
3209 trueValue, falseValue);
3210
3211 builder.clearAccessChain();
3212 builder.setAccessChainRValue(result);
3213 } else {
3214 // We need control flow to select the result.
3215 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003216 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3217 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003218
3219 // Selection control:
3220 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3221
3222 // make an "if" based on the value created by the condition
3223 spv::Builder::If ifBuilder(condition, control, builder);
3224
3225 // emit the "then" statement
3226 builder.createStore(trueValue, result);
3227 ifBuilder.makeBeginElse();
3228 // emit the "else" statement
3229 builder.createStore(falseValue, result);
3230
3231 // finish off the control flow
3232 ifBuilder.makeEndIf();
3233
3234 builder.clearAccessChain();
3235 builder.setAccessChainLValue(result);
3236 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003237 };
3238
John Kessenich4bee5312018-02-20 21:29:05 -07003239 // Execute the one side needed, as per the condition
3240 const auto executeOneSide = [&]() {
3241 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003242 if (node->getBasicType() != glslang::EbtVoid) {
3243 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3244 convertGlslangToSpvType(node->getType()));
3245 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003246
John Kessenich4bee5312018-02-20 21:29:05 -07003247 // Selection control:
3248 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3249
3250 // make an "if" based on the value created by the condition
3251 spv::Builder::If ifBuilder(condition, control, builder);
3252
3253 // emit the "then" statement
3254 if (node->getTrueBlock() != nullptr) {
3255 node->getTrueBlock()->traverse(this);
3256 if (result != spv::NoResult)
3257 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3258 }
3259
3260 if (node->getFalseBlock() != nullptr) {
3261 ifBuilder.makeBeginElse();
3262 // emit the "else" statement
3263 node->getFalseBlock()->traverse(this);
3264 if (result != spv::NoResult)
3265 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3266 }
3267
3268 // finish off the control flow
3269 ifBuilder.makeEndIf();
3270
3271 if (result != spv::NoResult) {
3272 builder.clearAccessChain();
3273 builder.setAccessChainLValue(result);
3274 }
3275 };
3276
3277 // Try for OpSelect (or a requirement to execute both sides)
3278 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003279 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3280 if (node->getType().getQualifier().isSpecConstant())
3281 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003282 executeBothSides();
3283 } else
3284 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003285
3286 return false;
3287}
3288
3289bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3290{
3291 // emit and get the condition before doing anything with switch
3292 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003293 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003294
Rex Xu57e65922017-07-04 23:23:40 +08003295 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003296 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003297
John Kessenich140f3df2015-06-26 16:58:36 -06003298 // browse the children to sort out code segments
3299 int defaultSegment = -1;
3300 std::vector<TIntermNode*> codeSegments;
3301 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3302 std::vector<int> caseValues;
3303 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3304 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3305 TIntermNode* child = *c;
3306 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003307 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003308 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003309 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003310 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3311 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003312 } else
3313 codeSegments.push_back(child);
3314 }
3315
qining25262b32016-05-06 17:25:16 -04003316 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003317 // statements between the last case and the end of the switch statement
3318 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3319 (int)codeSegments.size() == defaultSegment)
3320 codeSegments.push_back(nullptr);
3321
3322 // make the switch statement
3323 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003324 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3325 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003326
3327 // emit all the code in the segments
3328 breakForLoop.push(false);
3329 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3330 builder.nextSwitchSegment(segmentBlocks, s);
3331 if (codeSegments[s])
3332 codeSegments[s]->traverse(this);
3333 else
3334 builder.addSwitchBreak();
3335 }
3336 breakForLoop.pop();
3337
3338 builder.endSwitch(segmentBlocks);
3339
3340 return false;
3341}
3342
3343void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3344{
3345 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003346 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003347
3348 builder.clearAccessChain();
3349 builder.setAccessChainRValue(constant);
3350}
3351
3352bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3353{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003354 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003355 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003356
3357 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003358 std::vector<unsigned int> operands;
3359 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003360
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003361 // Spec requires back edges to target header blocks, and every header block
3362 // must dominate its merge block. Make a header block first to ensure these
3363 // conditions are met. By definition, it will contain OpLoopMerge, followed
3364 // by a block-ending branch. But we don't want to put any other body/test
3365 // instructions in it, since the body/test may have arbitrary instructions,
3366 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003367 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003368 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003369 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003370 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003371 spv::Block& test = builder.makeNewBlock();
3372 builder.createBranch(&test);
3373
3374 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003375 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003376 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003377 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3378
3379 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003380 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003381 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003382 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003383 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003384 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003385
3386 builder.setBuildPoint(&blocks.continue_target);
3387 if (node->getTerminal())
3388 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003389 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003390 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003391 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003392 builder.createBranch(&blocks.body);
3393
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003394 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003395 builder.setBuildPoint(&blocks.body);
3396 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003397 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003398 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003399 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003400
3401 builder.setBuildPoint(&blocks.continue_target);
3402 if (node->getTerminal())
3403 node->getTerminal()->traverse(this);
3404 if (node->getTest()) {
3405 node->getTest()->traverse(this);
3406 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003407 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003408 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003409 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003410 // TODO: unless there was a break/return/discard instruction
3411 // somewhere in the body, this is an infinite loop, so we should
3412 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003413 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003414 }
John Kessenich140f3df2015-06-26 16:58:36 -06003415 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003416 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003417 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003418 return false;
3419}
3420
3421bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3422{
3423 if (node->getExpression())
3424 node->getExpression()->traverse(this);
3425
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003426 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003427
John Kessenich140f3df2015-06-26 16:58:36 -06003428 switch (node->getFlowOp()) {
3429 case glslang::EOpKill:
3430 builder.makeDiscard();
3431 break;
3432 case glslang::EOpBreak:
3433 if (breakForLoop.top())
3434 builder.createLoopExit();
3435 else
3436 builder.addSwitchBreak();
3437 break;
3438 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003439 builder.createLoopContinue();
3440 break;
3441 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003442 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003443 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3444 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003445 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3446 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003447 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003448 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3449 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003450 builder.setAccessChainLValue(copyId);
3451 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003452 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003453 }
3454 builder.makeReturn(false, returnId);
3455 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003456 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003457
3458 builder.clearAccessChain();
3459 break;
3460
John Kessenichb9197c82019-08-11 07:41:45 -06003461#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003462 case glslang::EOpDemote:
3463 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3464 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3465 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3466 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003467#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003468
John Kessenich140f3df2015-06-26 16:58:36 -06003469 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003470 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003471 break;
3472 }
3473
3474 return false;
3475}
3476
John Kessenich9c14f772019-06-17 08:38:35 -06003477spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003478{
qining25262b32016-05-06 17:25:16 -04003479 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003480 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003481 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003482 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003483 spv::Id result = createSpvConstant(*node);
3484 if (result != spv::NoResult)
3485 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003486 }
3487
3488 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003489 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003490 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3491 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003492
John Kessenichb9197c82019-08-11 07:41:45 -06003493 const bool contains16BitType = node->getType().contains16BitFloat() ||
3494 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003495 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003496 switch (storageClass) {
3497 case spv::StorageClassInput:
3498 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003499 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003500 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003501 break;
John Kessenich18310872018-05-14 22:08:53 -06003502 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003503 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003504 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3505 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003506 else
3507 builder.addCapability(spv::CapabilityStorageUniform16);
3508 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003509#ifndef GLSLANG_WEB
3510 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003511 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003512 builder.addCapability(spv::CapabilityStoragePushConstant16);
3513 break;
John Kessenich18310872018-05-14 22:08:53 -06003514 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003515 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003516 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003517 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3518 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003519#endif
John Kessenich18310872018-05-14 22:08:53 -06003520 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003521 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003522 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003523 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003524 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003525 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003526 }
3527 }
Rex Xuf89ad982017-04-07 23:22:33 +08003528
John Kessenichb9197c82019-08-11 07:41:45 -06003529 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003530 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003531 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003532 builder.addCapability(spv::CapabilityStoragePushConstant8);
3533 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003534 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003535 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003536 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003537 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003538 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003539 } else {
3540 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003541 }
3542 }
3543
John Kessenich140f3df2015-06-26 16:58:36 -06003544 const char* name = node->getName().c_str();
3545 if (glslang::IsAnonymous(name))
3546 name = "";
3547
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003548 spv::Id initializer = spv::NoResult;
3549
3550 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3551 !node->getConstArray().empty()) {
3552 int nextConst = 0;
3553 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3554 node->getConstArray(),
3555 nextConst,
3556 false /* specConst */);
3557 }
3558
John Kessenich435dd802020-06-30 01:27:08 -06003559 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003560}
3561
3562// Return type Id of the sampled type.
3563spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3564{
3565 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003566 case glslang::EbtInt: return builder.makeIntType(32);
3567 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003568 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003569#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003570 case glslang::EbtFloat16:
3571 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3572 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3573 return builder.makeFloatType(16);
3574#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003575 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003576 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003577 return builder.makeFloatType(32);
3578 }
3579}
3580
John Kessenich8c8505c2016-07-26 12:50:38 -06003581// If node is a swizzle operation, return the type that should be used if
3582// the swizzle base is first consumed by another operation, before the swizzle
3583// is applied.
3584spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3585{
John Kessenichecba76f2017-01-06 00:34:48 -07003586 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003587 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3588 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3589 else
3590 return spv::NoType;
3591}
3592
3593// When inverting a swizzle with a parent op, this function
3594// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003595spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3596 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003597{
3598 std::vector<unsigned> swizzle;
3599 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3600 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3601}
3602
John Kessenich8c8505c2016-07-26 12:50:38 -06003603// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3604void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3605{
3606 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3607 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3608 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3609}
3610
John Kessenich3ac051e2015-12-20 11:29:16 -07003611// Convert from a glslang type to an SPV type, by calling into a
3612// recursive version of this function. This establishes the inherited
3613// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003614spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003615{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003616 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003617}
3618
3619// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003620// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003621// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003622spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003623 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3624 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003625{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003626 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003627
3628 switch (type.getBasicType()) {
3629 case glslang::EbtVoid:
3630 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003631 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003632 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003633 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003634 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3635 // a 32-bit int where non-0 means true.
3636 if (explicitLayout != glslang::ElpNone)
3637 spvType = builder.makeUintType(32);
3638 else
3639 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003640 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003641 case glslang::EbtInt:
3642 spvType = builder.makeIntType(32);
3643 break;
3644 case glslang::EbtUint:
3645 spvType = builder.makeUintType(32);
3646 break;
3647 case glslang::EbtFloat:
3648 spvType = builder.makeFloatType(32);
3649 break;
3650#ifndef GLSLANG_WEB
3651 case glslang::EbtDouble:
3652 spvType = builder.makeFloatType(64);
3653 break;
3654 case glslang::EbtFloat16:
3655 spvType = builder.makeFloatType(16);
3656 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003657 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003658 spvType = builder.makeIntType(8);
3659 break;
3660 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003661 spvType = builder.makeUintType(8);
3662 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003663 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003664 spvType = builder.makeIntType(16);
3665 break;
3666 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003667 spvType = builder.makeUintType(16);
3668 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003669 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003670 spvType = builder.makeIntType(64);
3671 break;
3672 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003673 spvType = builder.makeUintType(64);
3674 break;
John Kessenich426394d2015-07-23 10:22:48 -06003675 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003676 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003677 spvType = builder.makeUintType(32);
3678 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003679 case glslang::EbtAccStruct:
3680 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003681 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003682 case glslang::EbtRayQuery:
3683 spvType = builder.makeRayQueryType();
3684 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003685 case glslang::EbtReference:
3686 {
3687 // Make the forward pointer, then recurse to convert the structure type, then
3688 // patch up the forward pointer with a real pointer type.
3689 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3690 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3691 forwardPointers[type.getReferentType()] = forwardId;
3692 }
3693 spvType = forwardPointers[type.getReferentType()];
3694 if (!forwardReferenceOnly) {
3695 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3696 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3697 forwardPointers[type.getReferentType()],
3698 referentType);
3699 }
3700 }
3701 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003702#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003703 case glslang::EbtSampler:
3704 {
3705 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003706 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003707 spvType = builder.makeSamplerType();
3708 } else {
3709 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003710 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3711 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3712 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3713 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003714 // already has both image and sampler, make the combined type
3715 spvType = builder.makeSampledImageType(spvType);
3716 }
John Kessenich55e7d112015-11-15 21:33:39 -07003717 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003718 }
John Kessenich140f3df2015-06-26 16:58:36 -06003719 break;
3720 case glslang::EbtStruct:
3721 case glslang::EbtBlock:
3722 {
3723 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003724 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003725
3726 // Try to share structs for different layouts, but not yet for other
3727 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003728 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003729 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003730 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003731 break;
3732
3733 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003734 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003735 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003736 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003737 }
3738 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003739 case glslang::EbtString:
3740 // no type used for OpString
3741 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003742 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003743 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003744 break;
3745 }
3746
3747 if (type.isMatrix())
3748 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3749 else {
3750 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3751 if (type.getVectorSize() > 1)
3752 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3753 }
3754
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003755 if (type.isCoopMat()) {
3756 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3757 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3758 if (type.getBasicType() == glslang::EbtFloat16)
3759 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003760 if (type.getBasicType() == glslang::EbtUint8 ||
3761 type.getBasicType() == glslang::EbtInt8) {
3762 builder.addCapability(spv::CapabilityInt8);
3763 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003764
3765 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3766 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3767 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3768
3769 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3770 }
3771
John Kessenich140f3df2015-06-26 16:58:36 -06003772 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003773 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3774
John Kessenichc9a80832015-09-12 12:17:44 -06003775 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003776 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003777 // We need to decorate array strides for types needing explicit layout, except blocks.
3778 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003779 // Use a dummy glslang type for querying internal strides of
3780 // arrays of arrays, but using just a one-dimensional array.
3781 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003782 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3783 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003784
3785 // Will compute the higher-order strides here, rather than making a whole
3786 // pile of types and doing repetitive recursion on their contents.
3787 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3788 }
John Kessenichf8842e52016-01-04 19:22:56 -07003789
3790 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003791 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003792 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003793 if (stride > 0)
3794 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003795 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003796 }
3797 } else {
3798 // single-dimensional array, and don't yet have stride
3799
John Kessenichf8842e52016-01-04 19:22:56 -07003800 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003801 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3802 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003803 }
John Kessenich31ed4832015-09-09 17:51:38 -06003804
John Kessenichead86222018-03-28 18:01:20 -06003805 // Do the outer dimension, which might not be known for a runtime-sized array.
3806 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3807 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003808 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003809 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003810#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003811 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003812 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003813 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3814 }
John Kessenichb9197c82019-08-11 07:41:45 -06003815#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003816 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003817 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003818 if (stride > 0)
3819 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003820 }
3821
3822 return spvType;
3823}
3824
John Kessenich0e737842017-03-24 18:38:16 -06003825// TODO: this functionality should exist at a higher level, in creating the AST
3826//
3827// Identify interface members that don't have their required extension turned on.
3828//
3829bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3830{
John Kessenicha28f7a72019-08-06 07:00:58 -06003831#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003832 auto& extensions = glslangIntermediate->getRequestedExtensions();
3833
Rex Xubcf291a2017-03-29 23:01:36 +08003834 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3835 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3836 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003837 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3838 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3839 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003840
3841 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3842 if (member.getFieldName() == "gl_ViewportMask" &&
3843 extensions.find("GL_NV_viewport_array2") == extensions.end())
3844 return true;
3845 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3846 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3847 return true;
3848 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3849 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3850 return true;
3851 }
3852#endif
John Kessenich0e737842017-03-24 18:38:16 -06003853
3854 return false;
3855};
3856
John Kessenich6090df02016-06-30 21:18:02 -06003857// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3858// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3859// Mutually recursive with convertGlslangToSpvType().
3860spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3861 const glslang::TTypeList* glslangMembers,
3862 glslang::TLayoutPacking explicitLayout,
3863 const glslang::TQualifier& qualifier)
3864{
3865 // Create a vector of struct types for SPIR-V to consume
3866 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003867 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3868 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003869 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003870 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3871 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3872 if (glslangMember.hiddenMember()) {
3873 ++memberDelta;
3874 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003875 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003876 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003877 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003878 if (filterMember(glslangMember)) {
3879 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003880 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003881 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003882 }
Roy05a5b532020-01-03 16:21:34 +08003883 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003884 }
John Kessenich6090df02016-06-30 21:18:02 -06003885 // modify just this child's view of the qualifier
3886 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3887 InheritQualifiers(memberQualifier, qualifier);
3888
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003889 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003890 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003891 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003892
3893 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003894 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3895 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003896
3897 // Make forward pointers for any pointer members, and create a list of members to
3898 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003899 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003900 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3901 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3902 }
3903 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003904 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3905 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003906 } else {
3907 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003908 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3909 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003910 }
John Kessenich6090df02016-06-30 21:18:02 -06003911 }
3912 }
3913
3914 // Make the SPIR-V type
3915 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003916 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003917 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3918
3919 // Decorate it
3920 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3921
John Kessenichd72f4882019-01-16 14:55:37 +07003922 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003923 auto it = deferredForwardPointers[i];
3924 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3925 }
3926
John Kessenich6090df02016-06-30 21:18:02 -06003927 return spvType;
3928}
3929
3930void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3931 const glslang::TTypeList* glslangMembers,
3932 glslang::TLayoutPacking explicitLayout,
3933 const glslang::TQualifier& qualifier,
3934 spv::Id spvType)
3935{
3936 // Name and decorate the non-hidden members
3937 int offset = -1;
3938 int locationOffset = 0; // for use within the members of this struct
3939 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3940 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3941 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003942 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003943 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003944 if (filterMember(glslangMember))
3945 continue;
3946 }
John Kessenich6090df02016-06-30 21:18:02 -06003947
3948 // modify just this child's view of the qualifier
3949 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3950 InheritQualifiers(memberQualifier, qualifier);
3951
3952 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003953 if (member < 0)
3954 continue;
3955
3956 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3957 builder.addMemberDecoration(spvType, member,
3958 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3959 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3960 // Add interpolation and auxiliary storage decorations only to
3961 // top-level members of Input and Output storage classes
3962 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3963 type.getQualifier().storage == glslang::EvqVaryingOut) {
3964 if (type.getBasicType() == glslang::EbtBlock ||
3965 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3966 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3967 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003968#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003969 addMeshNVDecoration(spvType, member, memberQualifier);
3970#endif
John Kessenich6090df02016-06-30 21:18:02 -06003971 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003972 }
3973 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003974
John Kessenichb9197c82019-08-11 07:41:45 -06003975#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003976 if (type.getBasicType() == glslang::EbtBlock &&
3977 qualifier.storage == glslang::EvqBuffer) {
3978 // Add memory decorations only to top-level members of shader storage block
3979 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003980 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003981 for (unsigned int i = 0; i < memory.size(); ++i)
3982 builder.addMemberDecoration(spvType, member, memory[i]);
3983 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003984
John Kessenichb9197c82019-08-11 07:41:45 -06003985#endif
John Kessenich6090df02016-06-30 21:18:02 -06003986
John Kessenich5d610ee2018-03-07 18:05:55 -07003987 // Location assignment was already completed correctly by the front end,
3988 // just track whether a member needs to be decorated.
3989 // Ignore member locations if the container is an array, as that's
3990 // ill-specified and decisions have been made to not allow this.
3991 if (! type.isArray() && memberQualifier.hasLocation())
3992 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003993
John Kessenich5d610ee2018-03-07 18:05:55 -07003994 if (qualifier.hasLocation()) // track for upcoming inheritance
3995 locationOffset += glslangIntermediate->computeTypeLocationSize(
3996 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003997
John Kessenich5d610ee2018-03-07 18:05:55 -07003998 // component, XFB, others
3999 if (glslangMember.getQualifier().hasComponent())
4000 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4001 glslangMember.getQualifier().layoutComponent);
4002 if (glslangMember.getQualifier().hasXfbOffset())
4003 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4004 glslangMember.getQualifier().layoutXfbOffset);
4005 else if (explicitLayout != glslang::ElpNone) {
4006 // figure out what to do with offset, which is accumulating
4007 int nextOffset;
4008 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4009 if (offset >= 0)
4010 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4011 offset = nextOffset;
4012 }
John Kessenich6090df02016-06-30 21:18:02 -06004013
John Kessenich5d610ee2018-03-07 18:05:55 -07004014 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4015 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4016 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004017
John Kessenich5d610ee2018-03-07 18:05:55 -07004018 // built-in variable decorations
4019 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4020 if (builtIn != spv::BuiltInMax)
4021 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004022
John Kessenichb9197c82019-08-11 07:41:45 -06004023#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004024 // nonuniform
4025 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4026
John Kessenichead86222018-03-28 18:01:20 -06004027 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4028 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4029 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4030 memberQualifier.semanticName);
4031 }
4032
John Kessenich5d610ee2018-03-07 18:05:55 -07004033 if (builtIn == spv::BuiltInLayer) {
4034 // SPV_NV_viewport_array2 extension
4035 if (glslangMember.getQualifier().layoutViewportRelative){
4036 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4037 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4038 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004039 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004040 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4041 builder.addMemberDecoration(spvType, member,
4042 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4043 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4044 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4045 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004046 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004047 }
4048 if (glslangMember.getQualifier().layoutPassthrough) {
4049 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4050 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4051 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4052 }
chaoc771d89f2017-01-13 01:10:53 -08004053#endif
John Kessenich6090df02016-06-30 21:18:02 -06004054 }
4055
4056 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004057 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4058 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004059}
4060
John Kessenich6c292d32016-02-15 20:58:50 -07004061// Turn the expression forming the array size into an id.
4062// This is not quite trivial, because of specialization constants.
4063// Sometimes, a raw constant is turned into an Id, and sometimes
4064// a specialization constant expression is.
4065spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4066{
4067 // First, see if this is sized with a node, meaning a specialization constant:
4068 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4069 if (specNode != nullptr) {
4070 builder.clearAccessChain();
4071 specNode->traverse(this);
4072 return accessChainLoad(specNode->getAsTyped()->getType());
4073 }
qining25262b32016-05-06 17:25:16 -04004074
John Kessenich6c292d32016-02-15 20:58:50 -07004075 // Otherwise, need a compile-time (front end) size, get it:
4076 int size = arraySizes.getDimSize(dim);
4077 assert(size > 0);
4078 return builder.makeUintConstant(size);
4079}
4080
John Kessenich103bef92016-02-08 21:38:15 -07004081// Wrap the builder's accessChainLoad to:
4082// - localize handling of RelaxedPrecision
4083// - use the SPIR-V inferred type instead of another conversion of the glslang type
4084// (avoids unnecessary work and possible type punning for structures)
4085// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004086spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4087{
John Kessenich103bef92016-02-08 21:38:15 -07004088 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004089
4090 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4091 coherentFlags |= TranslateCoherent(type);
4092
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004093 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004094 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004095
John Kessenich5611c6d2018-04-05 11:25:02 -06004096 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004097 TranslateNonUniformDecoration(type.getQualifier()),
4098 nominalTypeId,
4099 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4100 TranslateMemoryScope(coherentFlags),
4101 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004102
4103 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004104 if (type.getBasicType() == glslang::EbtBool) {
4105 if (builder.isScalarType(nominalTypeId)) {
4106 // Conversion for bool
4107 spv::Id boolType = builder.makeBoolType();
4108 if (nominalTypeId != boolType)
4109 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4110 } else if (builder.isVectorType(nominalTypeId)) {
4111 // Conversion for bvec
4112 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4113 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4114 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004115 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4116 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004117 }
4118 }
John Kessenich103bef92016-02-08 21:38:15 -07004119
4120 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004121}
4122
Rex Xu27253232016-02-23 17:51:09 +08004123// Wrap the builder's accessChainStore to:
4124// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004125//
4126// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004127void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4128{
4129 // Need to convert to abstract types when necessary
4130 if (type.getBasicType() == glslang::EbtBool) {
4131 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4132
4133 if (builder.isScalarType(nominalTypeId)) {
4134 // Conversion for bool
4135 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004136 if (nominalTypeId != boolType) {
4137 // keep these outside arguments, for determinant order-of-evaluation
4138 spv::Id one = builder.makeUintConstant(1);
4139 spv::Id zero = builder.makeUintConstant(0);
4140 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4141 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004142 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004143 } else if (builder.isVectorType(nominalTypeId)) {
4144 // Conversion for bvec
4145 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4146 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004147 if (nominalTypeId != bvecType) {
4148 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004149 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4150 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4151 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004152 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004153 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4154 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004155 }
4156 }
4157
Jeff Bolz36831c92018-09-05 10:11:41 -05004158 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4159 coherentFlags |= TranslateCoherent(type);
4160
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004161 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004162 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004163
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02004164 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(type.getQualifier()),
John Kessenich8985fc92020-03-03 10:25:07 -07004165 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4166 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004167 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004168}
4169
John Kessenich4bf71552016-09-02 11:20:21 -06004170// For storing when types match at the glslang level, but not might match at the
4171// SPIR-V level.
4172//
4173// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004174// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004175// as in a member-decorated way.
4176//
4177// NOTE: This function can handle any store request; if it's not special it
4178// simplifies to a simple OpStore.
4179//
4180// Implicitly uses the existing builder.accessChain as the storage target.
4181void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4182{
John Kessenichb3e24e42016-09-11 12:33:43 -06004183 // we only do the complex path here if it's an aggregate
4184 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004185 accessChainStore(type, rValue);
4186 return;
4187 }
4188
John Kessenichb3e24e42016-09-11 12:33:43 -06004189 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004190 spv::Id rType = builder.getTypeId(rValue);
4191 spv::Id lValue = builder.accessChainGetLValue();
4192 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4193 if (lType == rType) {
4194 accessChainStore(type, rValue);
4195 return;
4196 }
4197
John Kessenichb3e24e42016-09-11 12:33:43 -06004198 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004199 // where the two types were the same type in GLSL. This requires member
4200 // by member copy, recursively.
4201
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004202 // SPIR-V 1.4 added an instruction to do help do this.
4203 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4204 // However, bool in uniform space is changed to int, so
4205 // OpCopyLogical does not work for that.
4206 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4207 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4208 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4209 if (lBool == rBool) {
4210 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4211 accessChainStore(type, logicalCopy);
4212 return;
4213 }
4214 }
4215
John Kessenichb3e24e42016-09-11 12:33:43 -06004216 // If an array, copy element by element.
4217 if (type.isArray()) {
4218 glslang::TType glslangElementType(type, 0);
4219 spv::Id elementRType = builder.getContainedTypeId(rType);
4220 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4221 // get the source member
4222 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004223
John Kessenichb3e24e42016-09-11 12:33:43 -06004224 // set up the target storage
4225 builder.clearAccessChain();
4226 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004227 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4228 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004229
John Kessenichb3e24e42016-09-11 12:33:43 -06004230 // store the member
4231 multiTypeStore(glslangElementType, elementRValue);
4232 }
4233 } else {
4234 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004235
John Kessenichb3e24e42016-09-11 12:33:43 -06004236 // loop over structure members
4237 const glslang::TTypeList& members = *type.getStruct();
4238 for (int m = 0; m < (int)members.size(); ++m) {
4239 const glslang::TType& glslangMemberType = *members[m].type;
4240
4241 // get the source member
4242 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4243 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4244
4245 // set up the target storage
4246 builder.clearAccessChain();
4247 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004248 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4249 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004250
4251 // store the member
4252 multiTypeStore(glslangMemberType, memberRValue);
4253 }
John Kessenich4bf71552016-09-02 11:20:21 -06004254 }
4255}
4256
John Kessenichf85e8062015-12-19 13:57:10 -07004257// Decide whether or not this type should be
4258// decorated with offsets and strides, and if so
4259// whether std140 or std430 rules should be applied.
4260glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004261{
John Kessenichf85e8062015-12-19 13:57:10 -07004262 // has to be a block
4263 if (type.getBasicType() != glslang::EbtBlock)
4264 return glslang::ElpNone;
4265
Chao Chen3c366992018-09-19 11:41:59 -07004266 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004267 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004268 type.getQualifier().storage != glslang::EvqBuffer &&
4269 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004270 return glslang::ElpNone;
4271
4272 // return the layout to use
4273 switch (type.getQualifier().layoutPacking) {
4274 case glslang::ElpStd140:
4275 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004276 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004277 return type.getQualifier().layoutPacking;
4278 default:
4279 return glslang::ElpNone;
4280 }
John Kessenich31ed4832015-09-09 17:51:38 -06004281}
4282
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004283// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004284int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4285 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004286{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004287 int size;
John Kessenich49987892015-12-29 17:11:44 -07004288 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004289 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4290 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004291
4292 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004293}
4294
John Kessenich49987892015-12-29 17:11:44 -07004295// 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 -07004296// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004297int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4298 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004299{
John Kessenich49987892015-12-29 17:11:44 -07004300 glslang::TType elementType;
4301 elementType.shallowCopy(matrixType);
4302 elementType.clearArraySizes();
4303
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004304 int size;
John Kessenich49987892015-12-29 17:11:44 -07004305 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004306 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4307 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004308
4309 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004310}
4311
John Kessenich5e4b1242015-08-06 22:53:06 -06004312// Given a member type of a struct, realign the current offset for it, and compute
4313// the next (not yet aligned) offset for the next member, which will get aligned
4314// on the next call.
4315// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4316// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4317// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004318void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4319 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004320{
4321 // this will get a positive value when deemed necessary
4322 nextOffset = -1;
4323
John Kessenich5e4b1242015-08-06 22:53:06 -06004324 // override anything in currentOffset with user-set offset
4325 if (memberType.getQualifier().hasOffset())
4326 currentOffset = memberType.getQualifier().layoutOffset;
4327
4328 // It could be that current linker usage in glslang updated all the layoutOffset,
4329 // in which case the following code does not matter. But, that's not quite right
4330 // once cross-compilation unit GLSL validation is done, as the original user
4331 // settings are needed in layoutOffset, and then the following will come into play.
4332
John Kessenichf85e8062015-12-19 13:57:10 -07004333 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004334 if (! memberType.getQualifier().hasOffset())
4335 currentOffset = -1;
4336
4337 return;
4338 }
4339
John Kessenichf85e8062015-12-19 13:57:10 -07004340 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004341 if (currentOffset < 0)
4342 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004343
John Kessenich5e4b1242015-08-06 22:53:06 -06004344 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4345 // but possibly not yet correctly aligned.
4346
4347 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004348 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004349 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4350 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004351
4352 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004353 // TODO: make this consistent in early phases of code:
4354 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4355 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4356 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004357 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004358 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004359 int dummySize;
4360 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4361 if (componentAlignment <= 4)
4362 memberAlignment = componentAlignment;
4363 }
4364
4365 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004366 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004367
4368 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004369 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4370 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004371 glslang::RoundToPow2(currentOffset, 16);
4372
John Kessenich5e4b1242015-08-06 22:53:06 -06004373 nextOffset = currentOffset + memberSize;
4374}
4375
David Netoa901ffe2016-06-08 14:11:40 +01004376void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004377{
David Netoa901ffe2016-06-08 14:11:40 +01004378 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4379 switch (glslangBuiltIn)
4380 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004381 case glslang::EbvPointSize:
4382#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004383 case glslang::EbvClipDistance:
4384 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004385 case glslang::EbvViewportMaskNV:
4386 case glslang::EbvSecondaryPositionNV:
4387 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004388 case glslang::EbvPositionPerViewNV:
4389 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004390 case glslang::EbvTaskCountNV:
4391 case glslang::EbvPrimitiveCountNV:
4392 case glslang::EbvPrimitiveIndicesNV:
4393 case glslang::EbvClipDistancePerViewNV:
4394 case glslang::EbvCullDistancePerViewNV:
4395 case glslang::EbvLayerPerViewNV:
4396 case glslang::EbvMeshViewCountNV:
4397 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004398#endif
David Netoa901ffe2016-06-08 14:11:40 +01004399 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4400 // Alternately, we could just call this for any glslang built-in, since the
4401 // capability already guards against duplicates.
4402 TranslateBuiltInDecoration(glslangBuiltIn, false);
4403 break;
4404 default:
4405 // Capabilities were already generated when the struct was declared.
4406 break;
4407 }
John Kessenichebb50532016-05-16 19:22:05 -06004408}
4409
John Kessenich6fccb3c2016-09-19 16:01:41 -06004410bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004411{
John Kessenicheee9d532016-09-19 18:09:30 -06004412 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004413}
4414
John Kessenichd41993d2017-09-10 15:21:05 -06004415// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004416// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4417// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004418bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004419{
John Kessenich6a14f782017-12-04 02:48:10 -07004420 assert(qualifier == glslang::EvqIn ||
4421 qualifier == glslang::EvqOut ||
4422 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004423 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004424 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004425 return qualifier != glslang::EvqConstReadOnly &&
4426 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004427}
4428
4429// Is parameter pass-by-original?
4430bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4431 bool implicitThisParam)
4432{
4433 if (implicitThisParam) // implicit this
4434 return true;
4435 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004436 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004437 return paramType.containsOpaque() || // sampler, etc.
4438 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4439}
4440
John Kessenich140f3df2015-06-26 16:58:36 -06004441// Make all the functions, skeletally, without actually visiting their bodies.
4442void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4443{
John Kessenich8985fc92020-03-03 10:25:07 -07004444 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4445 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004446 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4447 if (paramPrecision != spv::NoPrecision)
4448 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004449 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004450 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004451 // Original and non-writable params pass the pointer directly and
4452 // use restrict/aliased, others are stored to a pointer in Function
4453 // memory and use RestrictPointer/AliasedPointer.
4454 if (originalParam(type.getQualifier().storage, type, false) ||
4455 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004456 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4457 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004458 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004459 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4460 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004461 }
4462 }
John Kessenichfad62972017-07-18 02:35:46 -06004463 };
4464
John Kessenich140f3df2015-06-26 16:58:36 -06004465 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4466 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004467 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004468 continue;
4469
4470 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004471 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004472 //
qining25262b32016-05-06 17:25:16 -04004473 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004474 // function. What it is an address of varies:
4475 //
John Kessenich4bf71552016-09-02 11:20:21 -06004476 // - "in" parameters not marked as "const" can be written to without modifying the calling
4477 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004478 //
4479 // - "const in" parameters can just be the r-value, as no writes need occur.
4480 //
John Kessenich4bf71552016-09-02 11:20:21 -06004481 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4482 // 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 -06004483
4484 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004485 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004486 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4487
John Kessenich155d3512019-08-08 23:29:20 -06004488#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004489 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4490 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004491#else
4492 bool implicitThis = false;
4493#endif
John Kessenich37789792017-03-21 23:56:40 -06004494
John Kessenichfad62972017-07-18 02:35:46 -06004495 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004496 for (int p = 0; p < (int)parameters.size(); ++p) {
4497 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4498 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004499 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004500 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004501 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004502 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4503 else
John Kessenich4bf71552016-09-02 11:20:21 -06004504 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004505 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004506 paramTypes.push_back(typeId);
4507 }
4508
4509 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004510 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4511 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004512 glslFunction->getName().c_str(), paramTypes,
4513 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004514 if (implicitThis)
4515 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004516
4517 // Track function to emit/call later
4518 functionMap[glslFunction->getName().c_str()] = function;
4519
4520 // Set the parameter id's
4521 for (int p = 0; p < (int)parameters.size(); ++p) {
4522 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4523 // give a name too
4524 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004525
4526 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004527 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004528 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004529 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004530 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004531 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004532 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004533 }
4534 }
4535}
4536
4537// Process all the initializers, while skipping the functions and link objects
4538void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4539{
4540 builder.setBuildPoint(shaderEntry->getLastBlock());
4541 for (int i = 0; i < (int)initializers.size(); ++i) {
4542 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004543 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4544 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004545
4546 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004547 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004548 initializer->traverse(this);
4549 }
4550 }
4551}
4552
4553// Process all the functions, while skipping initializers.
4554void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4555{
4556 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4557 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004558 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004559 node->traverse(this);
4560 }
4561}
4562
4563void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4564{
qining25262b32016-05-06 17:25:16 -04004565 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004566 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004567 currentFunction = functionMap[node->getName().c_str()];
4568 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004569 builder.setBuildPoint(functionBlock);
4570}
4571
John Kessenich8985fc92020-03-03 10:25:07 -07004572void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4573 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004574{
Rex Xufc618912015-09-09 16:42:49 +08004575 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004576
4577 glslang::TSampler sampler = {};
4578 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004579#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004580 bool f16ShadowCompare = false;
4581#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004582 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004583 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4584 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004585#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004586 f16ShadowCompare = sampler.shadow &&
4587 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004588#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004589 }
4590
John Kessenich140f3df2015-06-26 16:58:36 -06004591 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4592 builder.clearAccessChain();
4593 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004594
John Kessenicha28f7a72019-08-06 07:00:58 -06004595#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004596 // Special case l-value operands
4597 bool lvalue = false;
4598 switch (node.getOp()) {
4599 case glslang::EOpImageAtomicAdd:
4600 case glslang::EOpImageAtomicMin:
4601 case glslang::EOpImageAtomicMax:
4602 case glslang::EOpImageAtomicAnd:
4603 case glslang::EOpImageAtomicOr:
4604 case glslang::EOpImageAtomicXor:
4605 case glslang::EOpImageAtomicExchange:
4606 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004607 case glslang::EOpImageAtomicLoad:
4608 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004609 if (i == 0)
4610 lvalue = true;
4611 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004612 case glslang::EOpSparseImageLoad:
4613 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4614 lvalue = true;
4615 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004616 case glslang::EOpSparseTexture:
4617 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4618 lvalue = true;
4619 break;
4620 case glslang::EOpSparseTextureClamp:
4621 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4622 lvalue = true;
4623 break;
4624 case glslang::EOpSparseTextureLod:
4625 case glslang::EOpSparseTextureOffset:
4626 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4627 lvalue = true;
4628 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004629 case glslang::EOpSparseTextureFetch:
4630 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4631 lvalue = true;
4632 break;
4633 case glslang::EOpSparseTextureFetchOffset:
4634 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4635 lvalue = true;
4636 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004637 case glslang::EOpSparseTextureLodOffset:
4638 case glslang::EOpSparseTextureGrad:
4639 case glslang::EOpSparseTextureOffsetClamp:
4640 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4641 lvalue = true;
4642 break;
4643 case glslang::EOpSparseTextureGradOffset:
4644 case glslang::EOpSparseTextureGradClamp:
4645 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4646 lvalue = true;
4647 break;
4648 case glslang::EOpSparseTextureGradOffsetClamp:
4649 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4650 lvalue = true;
4651 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004652 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004653 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4654 lvalue = true;
4655 break;
4656 case glslang::EOpSparseTextureGatherOffset:
4657 case glslang::EOpSparseTextureGatherOffsets:
4658 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4659 lvalue = true;
4660 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004661 case glslang::EOpSparseTextureGatherLod:
4662 if (i == 3)
4663 lvalue = true;
4664 break;
4665 case glslang::EOpSparseTextureGatherLodOffset:
4666 case glslang::EOpSparseTextureGatherLodOffsets:
4667 if (i == 4)
4668 lvalue = true;
4669 break;
Rex Xu129799a2017-07-05 17:23:28 +08004670 case glslang::EOpSparseImageLoadLod:
4671 if (i == 3)
4672 lvalue = true;
4673 break;
Chao Chen3a137962018-09-19 11:41:27 -07004674 case glslang::EOpImageSampleFootprintNV:
4675 if (i == 4)
4676 lvalue = true;
4677 break;
4678 case glslang::EOpImageSampleFootprintClampNV:
4679 case glslang::EOpImageSampleFootprintLodNV:
4680 if (i == 5)
4681 lvalue = true;
4682 break;
4683 case glslang::EOpImageSampleFootprintGradNV:
4684 if (i == 6)
4685 lvalue = true;
4686 break;
4687 case glslang::EOpImageSampleFootprintGradClampNV:
4688 if (i == 7)
4689 lvalue = true;
4690 break;
Rex Xufc618912015-09-09 16:42:49 +08004691 default:
4692 break;
4693 }
4694
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004695 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004696 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004697 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4698 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4699 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004700#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004701 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004702 }
4703}
4704
John Kessenichfc51d282015-08-19 13:34:18 -06004705void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004706{
John Kessenichfc51d282015-08-19 13:34:18 -06004707 builder.clearAccessChain();
4708 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004709 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004710}
John Kessenich140f3df2015-06-26 16:58:36 -06004711
John Kessenichfc51d282015-08-19 13:34:18 -06004712spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4713{
John Kesseniche485c7a2017-05-31 18:50:53 -06004714 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004715 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004716
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004717 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004718
John Kessenichfc51d282015-08-19 13:34:18 -06004719 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004720
John Kessenichf43c7392019-03-31 10:51:57 -06004721 const glslang::TType &imageType = node->getAsAggregate()
4722 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4723 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004724 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004725#ifdef GLSLANG_WEB
4726 const bool f16ShadowCompare = false;
4727#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004728 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004729 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4730 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004731#endif
4732
John Kessenichf43c7392019-03-31 10:51:57 -06004733 const auto signExtensionMask = [&]() {
4734 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4735 if (sampler.type == glslang::EbtUint)
4736 return spv::ImageOperandsZeroExtendMask;
4737 else if (sampler.type == glslang::EbtInt)
4738 return spv::ImageOperandsSignExtendMask;
4739 }
4740 return spv::ImageOperandsMaskNone;
4741 };
4742
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004743 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4744
John Kessenichfc51d282015-08-19 13:34:18 -06004745 std::vector<spv::Id> arguments;
4746 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004747 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004748 else
4749 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004750 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004751
4752 spv::Builder::TextureParameters params = { };
4753 params.sampler = arguments[0];
4754
Rex Xu04db3f52015-09-16 11:44:02 +08004755 glslang::TCrackedTextureOp cracked;
4756 node->crackTexture(sampler, cracked);
4757
amhagan05506bb2017-06-13 16:53:02 -04004758 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004759
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004760 if (builder.isSampledImage(params.sampler) &&
4761 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4762 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4763 if (imageType.getQualifier().isNonUniform()) {
4764 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4765 }
4766 }
John Kessenichfc51d282015-08-19 13:34:18 -06004767 // Check for queries
4768 if (cracked.query) {
4769 switch (node->getOp()) {
4770 case glslang::EOpImageQuerySize:
4771 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004772 if (arguments.size() > 1) {
4773 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004774 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004775 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004776 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004777#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004778 case glslang::EOpImageQuerySamples:
4779 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004780 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004781 case glslang::EOpTextureQueryLod:
4782 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004783 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004784 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004785 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004786 case glslang::EOpSparseTexelsResident:
4787 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004788#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004789 default:
4790 assert(0);
4791 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004792 }
John Kessenich140f3df2015-06-26 16:58:36 -06004793 }
4794
LoopDawg4425f242018-02-18 11:40:01 -07004795 int components = node->getType().getVectorSize();
4796
4797 if (node->getOp() == glslang::EOpTextureFetch) {
4798 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4799 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4800 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4801 // here around e.g. which ones return scalars or other types.
4802 components = 4;
4803 }
4804
4805 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4806
4807 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4808
Rex Xufc618912015-09-09 16:42:49 +08004809 // Check for image functions other than queries
4810 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004811 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004812 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004813 spv::IdImmediate image = { true, *(opIt++) };
4814 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004815
4816 // Handle subpass operations
4817 // TODO: GLSL should change to have the "MS" only on the type rather than the
4818 // built-in function.
4819 if (cracked.subpass) {
4820 // add on the (0,0) coordinate
4821 spv::Id zero = builder.makeIntConstant(0);
4822 std::vector<spv::Id> comps;
4823 comps.push_back(zero);
4824 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004825 spv::IdImmediate coord = { true,
4826 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4827 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004828 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4829 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004830 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004831 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4832 }
4833 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004834 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004835 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004836 spv::IdImmediate imageOperand = { true, *(opIt++) };
4837 operands.push_back(imageOperand);
4838 }
John Kessenich6c292d32016-02-15 20:58:50 -07004839 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004840 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4841 builder.setPrecision(result, precision);
4842 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004843 }
4844
John Kessenich149afc32018-08-14 13:31:43 -06004845 spv::IdImmediate coord = { true, *(opIt++) };
4846 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004847 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004848 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004849 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004850 mask = mask | spv::ImageOperandsSampleMask;
4851 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004852 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004853 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4854 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004855 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004856 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004857 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4858 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004859 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004860 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004861 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4862 operands.push_back(imageOperands);
4863 }
4864 if (mask & spv::ImageOperandsSampleMask) {
4865 spv::IdImmediate imageOperand = { true, *opIt++ };
4866 operands.push_back(imageOperand);
4867 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004868 if (mask & spv::ImageOperandsLodMask) {
4869 spv::IdImmediate imageOperand = { true, *opIt++ };
4870 operands.push_back(imageOperand);
4871 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004872 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004873 spv::IdImmediate imageOperand = { true,
4874 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004875 operands.push_back(imageOperand);
4876 }
4877
John Kessenich149afc32018-08-14 13:31:43 -06004878 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004879 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004880
John Kessenich149afc32018-08-14 13:31:43 -06004881 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004882 builder.setPrecision(result[0], precision);
4883
4884 // If needed, add a conversion constructor to the proper size.
4885 if (components != node->getType().getVectorSize())
4886 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4887
4888 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004889 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004890
Jeff Bolz36831c92018-09-05 10:11:41 -05004891 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004892 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004893 spv::IdImmediate texel = { true, *(opIt + 1) };
4894 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004895 } else {
4896 spv::IdImmediate texel = { true, *opIt };
4897 operands.push_back(texel);
4898 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004899
4900 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004901 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004902 mask = mask | spv::ImageOperandsSampleMask;
4903 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004904 if (cracked.lod) {
4905 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4906 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4907 mask = mask | spv::ImageOperandsLodMask;
4908 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004909 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4910 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004911 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004912 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004913 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4914 operands.push_back(imageOperands);
4915 }
4916 if (mask & spv::ImageOperandsSampleMask) {
4917 spv::IdImmediate imageOperand = { true, *opIt++ };
4918 operands.push_back(imageOperand);
4919 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004920 if (mask & spv::ImageOperandsLodMask) {
4921 spv::IdImmediate imageOperand = { true, *opIt++ };
4922 operands.push_back(imageOperand);
4923 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004924 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004925 spv::IdImmediate imageOperand = { true,
4926 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004927 operands.push_back(imageOperand);
4928 }
4929
John Kessenich56bab042015-09-16 10:54:31 -06004930 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004931 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004932 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004933 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004934 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4935 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004936 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004937 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004938 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4939
Jeff Bolz36831c92018-09-05 10:11:41 -05004940 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004941 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004942 mask = mask | spv::ImageOperandsSampleMask;
4943 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004944 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004945 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4946 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4947
Jeff Bolz36831c92018-09-05 10:11:41 -05004948 mask = mask | spv::ImageOperandsLodMask;
4949 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004950 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4951 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004952 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004953 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004954 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004955 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004956 }
4957 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004958 spv::IdImmediate imageOperand = { true, *opIt++ };
4959 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004960 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004961 if (mask & spv::ImageOperandsLodMask) {
4962 spv::IdImmediate imageOperand = { true, *opIt++ };
4963 operands.push_back(imageOperand);
4964 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004965 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004966 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4967 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004968 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004969 }
4970
4971 // Create the return type that was a special structure
4972 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004973 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004974 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4975 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4976
4977 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4978
4979 // Decode the return type
4980 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4981 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004982 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004983 // Process image atomic operations
4984
4985 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4986 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004987 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004988 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004989 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004990
Jeff Bolz36831c92018-09-05 10:11:41 -05004991 spv::Id resultTypeId;
4992 // imageAtomicStore has a void return type so base the pointer type on
4993 // the type of the value operand.
4994 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004995 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004996 } else {
4997 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4998 }
John Kessenich56bab042015-09-16 10:54:31 -06004999 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005000 if (imageType.getQualifier().nonUniform) {
5001 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5002 }
Rex Xufc618912015-09-09 16:42:49 +08005003
5004 std::vector<spv::Id> operands;
5005 operands.push_back(pointer);
5006 for (; opIt != arguments.end(); ++opIt)
5007 operands.push_back(*opIt);
5008
John Kessenich8985fc92020-03-03 10:25:07 -07005009 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5010 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005011 }
5012 }
5013
John Kessenicha28f7a72019-08-06 07:00:58 -06005014#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005015 // Check for fragment mask functions other than queries
5016 if (cracked.fragMask) {
5017 assert(sampler.ms);
5018
5019 auto opIt = arguments.begin();
5020 std::vector<spv::Id> operands;
5021
amhagan05506bb2017-06-13 16:53:02 -04005022 operands.push_back(params.sampler);
5023 ++opIt;
5024
5025 if (sampler.isSubpass()) {
5026 // add on the (0,0) coordinate
5027 spv::Id zero = builder.makeIntConstant(0);
5028 std::vector<spv::Id> comps;
5029 comps.push_back(zero);
5030 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005031 operands.push_back(builder.makeCompositeConstant(
5032 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005033 }
5034
5035 for (; opIt != arguments.end(); ++opIt)
5036 operands.push_back(*opIt);
5037
5038 spv::Op fragMaskOp = spv::OpNop;
5039 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5040 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5041 else if (node->getOp() == glslang::EOpFragmentFetch)
5042 fragMaskOp = spv::OpFragmentFetchAMD;
5043
5044 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5045 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5046 return builder.createOp(fragMaskOp, resultType(), operands);
5047 }
5048#endif
5049
Rex Xufc618912015-09-09 16:42:49 +08005050 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005051 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005052 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005053 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005054
John Kessenichfc51d282015-08-19 13:34:18 -06005055 // check for bias argument
5056 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005057 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005058 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005059 if (cracked.gather)
5060 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005061
5062 if (f16ShadowCompare)
5063 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005064 if (cracked.offset)
5065 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005066 else if (cracked.offsets)
5067 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005068 if (cracked.grad)
5069 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005070 if (cracked.lodClamp)
5071 ++nonBiasArgCount;
5072 if (sparse)
5073 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005074 if (imageFootprint)
5075 //Following three extra arguments
5076 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5077 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005078 if ((int)arguments.size() > nonBiasArgCount)
5079 bias = true;
5080 }
5081
John Kessenicha28f7a72019-08-06 07:00:58 -06005082#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005083 if (cracked.gather) {
5084 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5085 if (bias || cracked.lod ||
5086 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5087 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005088 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005089 }
5090 }
5091#endif
5092
John Kessenichfc51d282015-08-19 13:34:18 -06005093 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005094
John Kessenichfc51d282015-08-19 13:34:18 -06005095 params.coords = arguments[1];
5096 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005097 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005098
5099 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005100 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005101 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005102 ++extraArgs;
5103 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005104 params.Dref = arguments[2];
5105 ++extraArgs;
5106 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005107 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005108 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005109 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005110 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005111 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005112 dRefComp = builder.getNumComponents(params.coords) - 1;
5113 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005114 params.Dref = builder.createCompositeExtract(params.coords,
5115 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005116 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005117
5118 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005119 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005120 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005121 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005122 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5123 !(glslangIntermediate->getStage() == EShLangCompute &&
5124 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005125 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5126 noImplicitLod = true;
5127 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005128
5129 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005130 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005131 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005132 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005133 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005134
5135 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005136 if (cracked.grad) {
5137 params.gradX = arguments[2 + extraArgs];
5138 params.gradY = arguments[3 + extraArgs];
5139 extraArgs += 2;
5140 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005141
5142 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005143 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005144 params.offset = arguments[2 + extraArgs];
5145 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005146 } else if (cracked.offsets) {
5147 params.offsets = arguments[2 + extraArgs];
5148 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005149 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005150
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005151#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005152 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005153 if (cracked.lodClamp) {
5154 params.lodClamp = arguments[2 + extraArgs];
5155 ++extraArgs;
5156 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005157 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005158 if (sparse) {
5159 params.texelOut = arguments[2 + extraArgs];
5160 ++extraArgs;
5161 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005162 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005163 if (cracked.gather && ! sampler.shadow) {
5164 // default component is 0, if missing, otherwise an argument
5165 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005166 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005167 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005168 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005169 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005170 }
Chao Chen3a137962018-09-19 11:41:27 -07005171 spv::Id resultStruct = spv::NoResult;
5172 if (imageFootprint) {
5173 //Following three extra arguments
5174 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5175 params.granularity = arguments[2 + extraArgs];
5176 params.coarse = arguments[3 + extraArgs];
5177 resultStruct = arguments[4 + extraArgs];
5178 extraArgs += 3;
5179 }
5180#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005181 // bias
5182 if (bias) {
5183 params.bias = arguments[2 + extraArgs];
5184 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005185 }
John Kessenichfc51d282015-08-19 13:34:18 -06005186
John Kessenicha28f7a72019-08-06 07:00:58 -06005187#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005188 if (imageFootprint) {
5189 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5190 builder.addCapability(spv::CapabilityImageFootprintNV);
5191
5192
5193 //resultStructType(OpenGL type) contains 5 elements:
5194 //struct gl_TextureFootprint2DNV {
5195 // uvec2 anchor;
5196 // uvec2 offset;
5197 // uvec2 mask;
5198 // uint lod;
5199 // uint granularity;
5200 //};
5201 //or
5202 //struct gl_TextureFootprint3DNV {
5203 // uvec3 anchor;
5204 // uvec3 offset;
5205 // uvec2 mask;
5206 // uint lod;
5207 // uint granularity;
5208 //};
5209 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5210 assert(builder.isStructType(resultStructType));
5211
5212 //resType (SPIR-V type) contains 6 elements:
5213 //Member 0 must be a Boolean type scalar(LOD),
5214 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5215 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5216 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5217 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5218 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5219 std::vector<spv::Id> members;
5220 members.push_back(resultType());
5221 for (int i = 0; i < 5; i++) {
5222 members.push_back(builder.getContainedTypeId(resultStructType, i));
5223 }
5224 spv::Id resType = builder.makeStructType(members, "ResType");
5225
5226 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005227 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5228 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005229
5230 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5231 for (int i = 0; i < 5; i++) {
5232 builder.clearAccessChain();
5233 builder.setAccessChainLValue(resultStruct);
5234
5235 //Accessing to a struct we created, no coherent flag is set
5236 spv::Builder::AccessChain::CoherentFlags flags;
5237 flags.clear();
5238
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005239 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005240 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005241 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005242 }
5243 return builder.createCompositeExtract(res, resultType(), 0);
5244 }
5245#endif
5246
John Kessenich65336482016-06-16 14:06:26 -06005247 // projective component (might not to move)
5248 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5249 // are divided by the last component of P."
5250 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5251 // unused components will appear after all used components."
5252 if (cracked.proj) {
5253 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5254 int projTargetComp;
5255 switch (sampler.dim) {
5256 case glslang::Esd1D: projTargetComp = 1; break;
5257 case glslang::Esd2D: projTargetComp = 2; break;
5258 case glslang::EsdRect: projTargetComp = 2; break;
5259 default: projTargetComp = projSourceComp; break;
5260 }
5261 // copy the projective coordinate if we have to
5262 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005263 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005264 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005265 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005266 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005267 }
5268 }
5269
John Kessenichf8d1d742019-10-21 06:55:11 -06005270#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005271 // nonprivate
5272 if (imageType.getQualifier().nonprivate) {
5273 params.nonprivate = true;
5274 }
5275
5276 // volatile
5277 if (imageType.getQualifier().volatil) {
5278 params.volatil = true;
5279 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005280#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005281
St0fFa1184dd2018-04-09 21:08:14 +02005282 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005283 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5284 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005285 );
LoopDawg4425f242018-02-18 11:40:01 -07005286
5287 if (components != node->getType().getVectorSize())
5288 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5289
5290 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005291}
5292
5293spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5294{
5295 // Grab the function's pointer from the previously created function
5296 spv::Function* function = functionMap[node->getName().c_str()];
5297 if (! function)
5298 return 0;
5299
5300 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5301 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5302
5303 // See comments in makeFunctions() for details about the semantics for parameter passing.
5304 //
5305 // These imply we need a four step process:
5306 // 1. Evaluate the arguments
5307 // 2. Allocate and make copies of in, out, and inout arguments
5308 // 3. Make the call
5309 // 4. Copy back the results
5310
John Kessenichd3ed90b2018-05-04 11:43:03 -06005311 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005312 std::vector<spv::Builder::AccessChain> lValues;
5313 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005314 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005315 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005316 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005317 // build l-value
5318 builder.clearAccessChain();
5319 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005320 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005321 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005322 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005323 // save l-value
5324 lValues.push_back(builder.getAccessChain());
5325 } else {
5326 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005327 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005328 }
5329 }
5330
5331 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5332 // copy the original into that space.
5333 //
5334 // Also, build up the list of actual arguments to pass in for the call
5335 int lValueCount = 0;
5336 int rValueCount = 0;
5337 std::vector<spv::Id> spvArgs;
5338 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5339 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005340 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005341 builder.setAccessChain(lValues[lValueCount]);
5342 arg = builder.accessChainGetLValue();
5343 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005344 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005345 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005346 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005347 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005348 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5349 // need to copy the input into output space
5350 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005351 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005352 builder.clearAccessChain();
5353 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005354 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005355 }
5356 ++lValueCount;
5357 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005358 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005359 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005360 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005361 {
John Kessenich435dd802020-06-30 01:27:08 -06005362 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005363 builder.clearAccessChain();
5364 builder.setAccessChainLValue(argCopy);
5365 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005366 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005367 } else
5368 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005369 ++rValueCount;
5370 }
5371 spvArgs.push_back(arg);
5372 }
5373
5374 // 3. Make the call.
5375 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005376 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005377
5378 // 4. Copy back out an "out" arguments.
5379 lValueCount = 0;
5380 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005381 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005382 ++lValueCount;
5383 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005384 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005385 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005386 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005387 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005388 }
5389 ++lValueCount;
5390 }
5391 }
5392
5393 return result;
5394}
5395
5396// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005397spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005398 spv::Id typeId, spv::Id left, spv::Id right,
5399 glslang::TBasicType typeProxy, bool reduceComparison)
5400{
John Kessenich66011cb2018-03-06 16:12:04 -07005401 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5402 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005403 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005404
5405 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005406 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005407 bool comparison = false;
5408
5409 switch (op) {
5410 case glslang::EOpAdd:
5411 case glslang::EOpAddAssign:
5412 if (isFloat)
5413 binOp = spv::OpFAdd;
5414 else
5415 binOp = spv::OpIAdd;
5416 break;
5417 case glslang::EOpSub:
5418 case glslang::EOpSubAssign:
5419 if (isFloat)
5420 binOp = spv::OpFSub;
5421 else
5422 binOp = spv::OpISub;
5423 break;
5424 case glslang::EOpMul:
5425 case glslang::EOpMulAssign:
5426 if (isFloat)
5427 binOp = spv::OpFMul;
5428 else
5429 binOp = spv::OpIMul;
5430 break;
5431 case glslang::EOpVectorTimesScalar:
5432 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005433 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005434 if (builder.isVector(right))
5435 std::swap(left, right);
5436 assert(builder.isScalar(right));
5437 needMatchingVectors = false;
5438 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005439 } else if (isFloat)
5440 binOp = spv::OpFMul;
5441 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005442 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005443 break;
5444 case glslang::EOpVectorTimesMatrix:
5445 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005446 binOp = spv::OpVectorTimesMatrix;
5447 break;
5448 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005449 binOp = spv::OpMatrixTimesVector;
5450 break;
5451 case glslang::EOpMatrixTimesScalar:
5452 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005453 binOp = spv::OpMatrixTimesScalar;
5454 break;
5455 case glslang::EOpMatrixTimesMatrix:
5456 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005457 binOp = spv::OpMatrixTimesMatrix;
5458 break;
5459 case glslang::EOpOuterProduct:
5460 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005461 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 break;
5463
5464 case glslang::EOpDiv:
5465 case glslang::EOpDivAssign:
5466 if (isFloat)
5467 binOp = spv::OpFDiv;
5468 else if (isUnsigned)
5469 binOp = spv::OpUDiv;
5470 else
5471 binOp = spv::OpSDiv;
5472 break;
5473 case glslang::EOpMod:
5474 case glslang::EOpModAssign:
5475 if (isFloat)
5476 binOp = spv::OpFMod;
5477 else if (isUnsigned)
5478 binOp = spv::OpUMod;
5479 else
5480 binOp = spv::OpSMod;
5481 break;
5482 case glslang::EOpRightShift:
5483 case glslang::EOpRightShiftAssign:
5484 if (isUnsigned)
5485 binOp = spv::OpShiftRightLogical;
5486 else
5487 binOp = spv::OpShiftRightArithmetic;
5488 break;
5489 case glslang::EOpLeftShift:
5490 case glslang::EOpLeftShiftAssign:
5491 binOp = spv::OpShiftLeftLogical;
5492 break;
5493 case glslang::EOpAnd:
5494 case glslang::EOpAndAssign:
5495 binOp = spv::OpBitwiseAnd;
5496 break;
5497 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005498 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005499 binOp = spv::OpLogicalAnd;
5500 break;
5501 case glslang::EOpInclusiveOr:
5502 case glslang::EOpInclusiveOrAssign:
5503 binOp = spv::OpBitwiseOr;
5504 break;
5505 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005506 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005507 binOp = spv::OpLogicalOr;
5508 break;
5509 case glslang::EOpExclusiveOr:
5510 case glslang::EOpExclusiveOrAssign:
5511 binOp = spv::OpBitwiseXor;
5512 break;
5513 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005514 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005515 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005516 break;
5517
Ian Romanickb3bd4022019-01-21 08:57:25 -08005518 case glslang::EOpAbsDifference:
5519 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5520 break;
5521
5522 case glslang::EOpAddSaturate:
5523 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5524 break;
5525
5526 case glslang::EOpSubSaturate:
5527 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5528 break;
5529
5530 case glslang::EOpAverage:
5531 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5532 break;
5533
5534 case glslang::EOpAverageRounded:
5535 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5536 break;
5537
5538 case glslang::EOpMul32x16:
5539 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5540 break;
5541
John Kessenich140f3df2015-06-26 16:58:36 -06005542 case glslang::EOpLessThan:
5543 case glslang::EOpGreaterThan:
5544 case glslang::EOpLessThanEqual:
5545 case glslang::EOpGreaterThanEqual:
5546 case glslang::EOpEqual:
5547 case glslang::EOpNotEqual:
5548 case glslang::EOpVectorEqual:
5549 case glslang::EOpVectorNotEqual:
5550 comparison = true;
5551 break;
5552 default:
5553 break;
5554 }
5555
John Kessenich7c1aa102015-10-15 13:29:11 -06005556 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005557 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005558 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005559 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5560 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005561 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005562
5563 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005564 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005565 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005566
qining25262b32016-05-06 17:25:16 -04005567 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005568 decorations.addNoContraction(builder, result);
5569 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005570 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005571 }
5572
5573 if (! comparison)
5574 return 0;
5575
John Kessenich7c1aa102015-10-15 13:29:11 -06005576 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005577
John Kessenich4583b612016-08-07 19:14:22 -06005578 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005579 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5580 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005581 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005582 return result;
5583 }
John Kessenich140f3df2015-06-26 16:58:36 -06005584
5585 switch (op) {
5586 case glslang::EOpLessThan:
5587 if (isFloat)
5588 binOp = spv::OpFOrdLessThan;
5589 else if (isUnsigned)
5590 binOp = spv::OpULessThan;
5591 else
5592 binOp = spv::OpSLessThan;
5593 break;
5594 case glslang::EOpGreaterThan:
5595 if (isFloat)
5596 binOp = spv::OpFOrdGreaterThan;
5597 else if (isUnsigned)
5598 binOp = spv::OpUGreaterThan;
5599 else
5600 binOp = spv::OpSGreaterThan;
5601 break;
5602 case glslang::EOpLessThanEqual:
5603 if (isFloat)
5604 binOp = spv::OpFOrdLessThanEqual;
5605 else if (isUnsigned)
5606 binOp = spv::OpULessThanEqual;
5607 else
5608 binOp = spv::OpSLessThanEqual;
5609 break;
5610 case glslang::EOpGreaterThanEqual:
5611 if (isFloat)
5612 binOp = spv::OpFOrdGreaterThanEqual;
5613 else if (isUnsigned)
5614 binOp = spv::OpUGreaterThanEqual;
5615 else
5616 binOp = spv::OpSGreaterThanEqual;
5617 break;
5618 case glslang::EOpEqual:
5619 case glslang::EOpVectorEqual:
5620 if (isFloat)
5621 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005622 else if (isBool)
5623 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005624 else
5625 binOp = spv::OpIEqual;
5626 break;
5627 case glslang::EOpNotEqual:
5628 case glslang::EOpVectorNotEqual:
5629 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005630 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005631 else if (isBool)
5632 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005633 else
5634 binOp = spv::OpINotEqual;
5635 break;
5636 default:
5637 break;
5638 }
5639
qining25262b32016-05-06 17:25:16 -04005640 if (binOp != spv::OpNop) {
5641 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005642 decorations.addNoContraction(builder, result);
5643 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005644 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005645 }
John Kessenich140f3df2015-06-26 16:58:36 -06005646
5647 return 0;
5648}
5649
John Kessenich04bb8a02015-12-12 12:28:14 -07005650//
5651// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5652// These can be any of:
5653//
5654// matrix * scalar
5655// scalar * matrix
5656// matrix * matrix linear algebraic
5657// matrix * vector
5658// vector * matrix
5659// matrix * matrix componentwise
5660// matrix op matrix op in {+, -, /}
5661// matrix op scalar op in {+, -, /}
5662// scalar op matrix op in {+, -, /}
5663//
John Kessenichead86222018-03-28 18:01:20 -06005664spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5665 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005666{
5667 bool firstClass = true;
5668
5669 // First, handle first-class matrix operations (* and matrix/scalar)
5670 switch (op) {
5671 case spv::OpFDiv:
5672 if (builder.isMatrix(left) && builder.isScalar(right)) {
5673 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005674 spv::Id resultType = builder.getTypeId(right);
5675 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005676 op = spv::OpMatrixTimesScalar;
5677 } else
5678 firstClass = false;
5679 break;
5680 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005681 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005682 std::swap(left, right);
5683 assert(builder.isScalar(right));
5684 break;
5685 case spv::OpVectorTimesMatrix:
5686 assert(builder.isVector(left));
5687 assert(builder.isMatrix(right));
5688 break;
5689 case spv::OpMatrixTimesVector:
5690 assert(builder.isMatrix(left));
5691 assert(builder.isVector(right));
5692 break;
5693 case spv::OpMatrixTimesMatrix:
5694 assert(builder.isMatrix(left));
5695 assert(builder.isMatrix(right));
5696 break;
5697 default:
5698 firstClass = false;
5699 break;
5700 }
5701
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005702 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5703 firstClass = true;
5704
qining25262b32016-05-06 17:25:16 -04005705 if (firstClass) {
5706 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005707 decorations.addNoContraction(builder, result);
5708 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005709 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005710 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005711
LoopDawg592860c2016-06-09 08:57:35 -06005712 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005713 // The result type of all of them is the same type as the (a) matrix operand.
5714 // The algorithm is to:
5715 // - break the matrix(es) into vectors
5716 // - smear any scalar to a vector
5717 // - do vector operations
5718 // - make a matrix out the vector results
5719 switch (op) {
5720 case spv::OpFAdd:
5721 case spv::OpFSub:
5722 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005723 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005724 case spv::OpFMul:
5725 {
5726 // one time set up...
5727 bool leftMat = builder.isMatrix(left);
5728 bool rightMat = builder.isMatrix(right);
5729 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5730 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5731 spv::Id scalarType = builder.getScalarTypeId(typeId);
5732 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5733 std::vector<spv::Id> results;
5734 spv::Id smearVec = spv::NoResult;
5735 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005736 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005737 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005738 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005739
5740 // do each vector op
5741 for (unsigned int c = 0; c < numCols; ++c) {
5742 std::vector<unsigned int> indexes;
5743 indexes.push_back(c);
5744 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5745 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005746 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005747 decorations.addNoContraction(builder, result);
5748 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005749 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005750 }
5751
5752 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005753 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005754 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005755 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005756 }
5757 default:
5758 assert(0);
5759 return spv::NoResult;
5760 }
5761}
5762
John Kessenichead86222018-03-28 18:01:20 -06005763spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005764 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005765{
5766 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005767 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005768 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005769 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5770 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005771
5772 switch (op) {
5773 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005774 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005775 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005776 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005777 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005778 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005779 unaryOp = spv::OpSNegate;
5780 break;
5781
5782 case glslang::EOpLogicalNot:
5783 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005784 unaryOp = spv::OpLogicalNot;
5785 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005786 case glslang::EOpBitwiseNot:
5787 unaryOp = spv::OpNot;
5788 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005789
John Kessenich140f3df2015-06-26 16:58:36 -06005790 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005791 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005792 break;
5793 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005794 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005795 break;
5796 case glslang::EOpTranspose:
5797 unaryOp = spv::OpTranspose;
5798 break;
5799
5800 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005801 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005802 break;
5803 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005804 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005805 break;
5806 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005807 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005808 break;
5809 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005810 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005811 break;
5812 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005813 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005814 break;
5815 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005816 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005817 break;
5818 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005819 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005820 break;
5821 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005822 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005823 break;
5824
5825 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005826 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005827 break;
5828 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005829 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005830 break;
5831 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005832 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005833 break;
5834 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005835 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005836 break;
5837 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005838 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005839 break;
5840 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005841 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005842 break;
5843
5844 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005845 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005846 break;
5847 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005848 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005849 break;
5850
5851 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005852 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005853 break;
5854 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005855 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
5857 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005858 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005859 break;
5860 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005861 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005862 break;
5863 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005864 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005865 break;
5866 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005867 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005868 break;
5869
5870 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005871 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005872 break;
5873 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005874 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005875 break;
5876 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005877 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005878 break;
5879 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005880 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005881 break;
5882 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005883 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005884 break;
5885 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005886 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005887 break;
5888
5889 case glslang::EOpIsNan:
5890 unaryOp = spv::OpIsNan;
5891 break;
5892 case glslang::EOpIsInf:
5893 unaryOp = spv::OpIsInf;
5894 break;
LoopDawg592860c2016-06-09 08:57:35 -06005895 case glslang::EOpIsFinite:
5896 unaryOp = spv::OpIsFinite;
5897 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005898
Rex Xucbc426e2015-12-15 16:03:10 +08005899 case glslang::EOpFloatBitsToInt:
5900 case glslang::EOpFloatBitsToUint:
5901 case glslang::EOpIntBitsToFloat:
5902 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005903 case glslang::EOpDoubleBitsToInt64:
5904 case glslang::EOpDoubleBitsToUint64:
5905 case glslang::EOpInt64BitsToDouble:
5906 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005907 case glslang::EOpFloat16BitsToInt16:
5908 case glslang::EOpFloat16BitsToUint16:
5909 case glslang::EOpInt16BitsToFloat16:
5910 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005911 unaryOp = spv::OpBitcast;
5912 break;
5913
John Kessenich140f3df2015-06-26 16:58:36 -06005914 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005915 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005916 break;
5917 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005918 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005919 break;
5920 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005921 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005922 break;
5923 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005924 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005925 break;
5926 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005927 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005928 break;
5929 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005930 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005931 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005932#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005933 case glslang::EOpPackSnorm4x8:
5934 libCall = spv::GLSLstd450PackSnorm4x8;
5935 break;
5936 case glslang::EOpUnpackSnorm4x8:
5937 libCall = spv::GLSLstd450UnpackSnorm4x8;
5938 break;
5939 case glslang::EOpPackUnorm4x8:
5940 libCall = spv::GLSLstd450PackUnorm4x8;
5941 break;
5942 case glslang::EOpUnpackUnorm4x8:
5943 libCall = spv::GLSLstd450UnpackUnorm4x8;
5944 break;
5945 case glslang::EOpPackDouble2x32:
5946 libCall = spv::GLSLstd450PackDouble2x32;
5947 break;
5948 case glslang::EOpUnpackDouble2x32:
5949 libCall = spv::GLSLstd450UnpackDouble2x32;
5950 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005951#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005952
Rex Xu8ff43de2016-04-22 16:51:45 +08005953 case glslang::EOpPackInt2x32:
5954 case glslang::EOpUnpackInt2x32:
5955 case glslang::EOpPackUint2x32:
5956 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005957 case glslang::EOpPack16:
5958 case glslang::EOpPack32:
5959 case glslang::EOpPack64:
5960 case glslang::EOpUnpack32:
5961 case glslang::EOpUnpack16:
5962 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005963 case glslang::EOpPackInt2x16:
5964 case glslang::EOpUnpackInt2x16:
5965 case glslang::EOpPackUint2x16:
5966 case glslang::EOpUnpackUint2x16:
5967 case glslang::EOpPackInt4x16:
5968 case glslang::EOpUnpackInt4x16:
5969 case glslang::EOpPackUint4x16:
5970 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005971 case glslang::EOpPackFloat2x16:
5972 case glslang::EOpUnpackFloat2x16:
5973 unaryOp = spv::OpBitcast;
5974 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005975
John Kessenich140f3df2015-06-26 16:58:36 -06005976 case glslang::EOpDPdx:
5977 unaryOp = spv::OpDPdx;
5978 break;
5979 case glslang::EOpDPdy:
5980 unaryOp = spv::OpDPdy;
5981 break;
5982 case glslang::EOpFwidth:
5983 unaryOp = spv::OpFwidth;
5984 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005985
John Kessenich140f3df2015-06-26 16:58:36 -06005986 case glslang::EOpAny:
5987 unaryOp = spv::OpAny;
5988 break;
5989 case glslang::EOpAll:
5990 unaryOp = spv::OpAll;
5991 break;
5992
5993 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005994 if (isFloat)
5995 libCall = spv::GLSLstd450FAbs;
5996 else
5997 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005998 break;
5999 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006000 if (isFloat)
6001 libCall = spv::GLSLstd450FSign;
6002 else
6003 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006004 break;
6005
John Kessenicha28f7a72019-08-06 07:00:58 -06006006#ifndef GLSLANG_WEB
6007 case glslang::EOpDPdxFine:
6008 unaryOp = spv::OpDPdxFine;
6009 break;
6010 case glslang::EOpDPdyFine:
6011 unaryOp = spv::OpDPdyFine;
6012 break;
6013 case glslang::EOpFwidthFine:
6014 unaryOp = spv::OpFwidthFine;
6015 break;
6016 case glslang::EOpDPdxCoarse:
6017 unaryOp = spv::OpDPdxCoarse;
6018 break;
6019 case glslang::EOpDPdyCoarse:
6020 unaryOp = spv::OpDPdyCoarse;
6021 break;
6022 case glslang::EOpFwidthCoarse:
6023 unaryOp = spv::OpFwidthCoarse;
6024 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006025 case glslang::EOpRayQueryProceed:
6026 unaryOp = spv::OpRayQueryProceedKHR;
6027 break;
6028 case glslang::EOpRayQueryGetRayTMin:
6029 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6030 break;
6031 case glslang::EOpRayQueryGetRayFlags:
6032 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6033 break;
6034 case glslang::EOpRayQueryGetWorldRayOrigin:
6035 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6036 break;
6037 case glslang::EOpRayQueryGetWorldRayDirection:
6038 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6039 break;
6040 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6041 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6042 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006043 case glslang::EOpInterpolateAtCentroid:
6044 if (typeProxy == glslang::EbtFloat16)
6045 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6046 libCall = spv::GLSLstd450InterpolateAtCentroid;
6047 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006048 case glslang::EOpAtomicCounterIncrement:
6049 case glslang::EOpAtomicCounterDecrement:
6050 case glslang::EOpAtomicCounter:
6051 {
6052 // Handle all of the atomics in one place, in createAtomicOperation()
6053 std::vector<spv::Id> operands;
6054 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006055 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006056 }
6057
John Kessenichfc51d282015-08-19 13:34:18 -06006058 case glslang::EOpBitFieldReverse:
6059 unaryOp = spv::OpBitReverse;
6060 break;
6061 case glslang::EOpBitCount:
6062 unaryOp = spv::OpBitCount;
6063 break;
6064 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006065 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006066 break;
6067 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006068 if (isUnsigned)
6069 libCall = spv::GLSLstd450FindUMsb;
6070 else
6071 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006072 break;
6073
Ian Romanickb3bd4022019-01-21 08:57:25 -08006074 case glslang::EOpCountLeadingZeros:
6075 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6076 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6077 unaryOp = spv::OpUCountLeadingZerosINTEL;
6078 break;
6079
6080 case glslang::EOpCountTrailingZeros:
6081 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6082 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6083 unaryOp = spv::OpUCountTrailingZerosINTEL;
6084 break;
6085
Rex Xu574ab042016-04-14 16:53:07 +08006086 case glslang::EOpBallot:
6087 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006088 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006089 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006090 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006091 case glslang::EOpMinInvocations:
6092 case glslang::EOpMaxInvocations:
6093 case glslang::EOpAddInvocations:
6094 case glslang::EOpMinInvocationsNonUniform:
6095 case glslang::EOpMaxInvocationsNonUniform:
6096 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006097 case glslang::EOpMinInvocationsInclusiveScan:
6098 case glslang::EOpMaxInvocationsInclusiveScan:
6099 case glslang::EOpAddInvocationsInclusiveScan:
6100 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6101 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6102 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6103 case glslang::EOpMinInvocationsExclusiveScan:
6104 case glslang::EOpMaxInvocationsExclusiveScan:
6105 case glslang::EOpAddInvocationsExclusiveScan:
6106 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6107 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6108 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006109 {
6110 std::vector<spv::Id> operands;
6111 operands.push_back(operand);
6112 return createInvocationsOperation(op, typeId, operands, typeProxy);
6113 }
John Kessenich66011cb2018-03-06 16:12:04 -07006114 case glslang::EOpSubgroupAll:
6115 case glslang::EOpSubgroupAny:
6116 case glslang::EOpSubgroupAllEqual:
6117 case glslang::EOpSubgroupBroadcastFirst:
6118 case glslang::EOpSubgroupBallot:
6119 case glslang::EOpSubgroupInverseBallot:
6120 case glslang::EOpSubgroupBallotBitCount:
6121 case glslang::EOpSubgroupBallotInclusiveBitCount:
6122 case glslang::EOpSubgroupBallotExclusiveBitCount:
6123 case glslang::EOpSubgroupBallotFindLSB:
6124 case glslang::EOpSubgroupBallotFindMSB:
6125 case glslang::EOpSubgroupAdd:
6126 case glslang::EOpSubgroupMul:
6127 case glslang::EOpSubgroupMin:
6128 case glslang::EOpSubgroupMax:
6129 case glslang::EOpSubgroupAnd:
6130 case glslang::EOpSubgroupOr:
6131 case glslang::EOpSubgroupXor:
6132 case glslang::EOpSubgroupInclusiveAdd:
6133 case glslang::EOpSubgroupInclusiveMul:
6134 case glslang::EOpSubgroupInclusiveMin:
6135 case glslang::EOpSubgroupInclusiveMax:
6136 case glslang::EOpSubgroupInclusiveAnd:
6137 case glslang::EOpSubgroupInclusiveOr:
6138 case glslang::EOpSubgroupInclusiveXor:
6139 case glslang::EOpSubgroupExclusiveAdd:
6140 case glslang::EOpSubgroupExclusiveMul:
6141 case glslang::EOpSubgroupExclusiveMin:
6142 case glslang::EOpSubgroupExclusiveMax:
6143 case glslang::EOpSubgroupExclusiveAnd:
6144 case glslang::EOpSubgroupExclusiveOr:
6145 case glslang::EOpSubgroupExclusiveXor:
6146 case glslang::EOpSubgroupQuadSwapHorizontal:
6147 case glslang::EOpSubgroupQuadSwapVertical:
6148 case glslang::EOpSubgroupQuadSwapDiagonal: {
6149 std::vector<spv::Id> operands;
6150 operands.push_back(operand);
6151 return createSubgroupOperation(op, typeId, operands, typeProxy);
6152 }
Rex Xu9d93a232016-05-05 12:30:44 +08006153 case glslang::EOpMbcnt:
6154 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6155 libCall = spv::MbcntAMD;
6156 break;
6157
6158 case glslang::EOpCubeFaceIndex:
6159 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6160 libCall = spv::CubeFaceIndexAMD;
6161 break;
6162
6163 case glslang::EOpCubeFaceCoord:
6164 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6165 libCall = spv::CubeFaceCoordAMD;
6166 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006167 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006168 unaryOp = spv::OpGroupNonUniformPartitionNV;
6169 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006170 case glslang::EOpConstructReference:
6171 unaryOp = spv::OpBitcast;
6172 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006173#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006174
6175 case glslang::EOpCopyObject:
6176 unaryOp = spv::OpCopyObject;
6177 break;
6178
John Kessenich140f3df2015-06-26 16:58:36 -06006179 default:
6180 return 0;
6181 }
6182
6183 spv::Id id;
6184 if (libCall >= 0) {
6185 std::vector<spv::Id> args;
6186 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006187 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006188 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006189 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006190 }
John Kessenich140f3df2015-06-26 16:58:36 -06006191
John Kessenichb9197c82019-08-11 07:41:45 -06006192 decorations.addNoContraction(builder, id);
6193 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006194 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006195}
6196
John Kessenich7a53f762016-01-20 11:19:27 -07006197// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006198spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6199 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006200{
6201 // Handle unary operations vector by vector.
6202 // The result type is the same type as the original type.
6203 // The algorithm is to:
6204 // - break the matrix into vectors
6205 // - apply the operation to each vector
6206 // - make a matrix out the vector results
6207
6208 // get the types sorted out
6209 int numCols = builder.getNumColumns(operand);
6210 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006211 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6212 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006213 std::vector<spv::Id> results;
6214
6215 // do each vector op
6216 for (int c = 0; c < numCols; ++c) {
6217 std::vector<unsigned int> indexes;
6218 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006219 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6220 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006221 decorations.addNoContraction(builder, destVec);
6222 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006223 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006224 }
6225
6226 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006227 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006228 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006229 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006230}
6231
John Kessenichad7645f2018-06-04 19:11:25 -06006232// For converting integers where both the bitwidth and the signedness could
6233// change, but only do the width change here. The caller is still responsible
6234// for the signedness conversion.
6235spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006236{
John Kessenichad7645f2018-06-04 19:11:25 -06006237 // Get the result type width, based on the type to convert to.
6238 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006239 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006240 case glslang::EOpConvInt16ToUint8:
6241 case glslang::EOpConvIntToUint8:
6242 case glslang::EOpConvInt64ToUint8:
6243 case glslang::EOpConvUint16ToInt8:
6244 case glslang::EOpConvUintToInt8:
6245 case glslang::EOpConvUint64ToInt8:
6246 width = 8;
6247 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006248 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006249 case glslang::EOpConvIntToUint16:
6250 case glslang::EOpConvInt64ToUint16:
6251 case glslang::EOpConvUint8ToInt16:
6252 case glslang::EOpConvUintToInt16:
6253 case glslang::EOpConvUint64ToInt16:
6254 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006255 break;
6256 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006257 case glslang::EOpConvInt16ToUint:
6258 case glslang::EOpConvInt64ToUint:
6259 case glslang::EOpConvUint8ToInt:
6260 case glslang::EOpConvUint16ToInt:
6261 case glslang::EOpConvUint64ToInt:
6262 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006263 break;
6264 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006265 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006266 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006267 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006268 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006269 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006270 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006271 break;
6272
6273 default:
6274 assert(false && "Default missing");
6275 break;
6276 }
6277
John Kessenichad7645f2018-06-04 19:11:25 -06006278 // Get the conversion operation and result type,
6279 // based on the target width, but the source type.
6280 spv::Id type = spv::NoType;
6281 spv::Op convOp = spv::OpNop;
6282 switch(op) {
6283 case glslang::EOpConvInt8ToUint16:
6284 case glslang::EOpConvInt8ToUint:
6285 case glslang::EOpConvInt8ToUint64:
6286 case glslang::EOpConvInt16ToUint8:
6287 case glslang::EOpConvInt16ToUint:
6288 case glslang::EOpConvInt16ToUint64:
6289 case glslang::EOpConvIntToUint8:
6290 case glslang::EOpConvIntToUint16:
6291 case glslang::EOpConvIntToUint64:
6292 case glslang::EOpConvInt64ToUint8:
6293 case glslang::EOpConvInt64ToUint16:
6294 case glslang::EOpConvInt64ToUint:
6295 convOp = spv::OpSConvert;
6296 type = builder.makeIntType(width);
6297 break;
6298 default:
6299 convOp = spv::OpUConvert;
6300 type = builder.makeUintType(width);
6301 break;
6302 }
6303
John Kessenich66011cb2018-03-06 16:12:04 -07006304 if (vectorSize > 0)
6305 type = builder.makeVectorType(type, vectorSize);
6306
John Kessenichad7645f2018-06-04 19:11:25 -06006307 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006308}
6309
John Kessenichead86222018-03-28 18:01:20 -06006310spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6311 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006312{
6313 spv::Op convOp = spv::OpNop;
6314 spv::Id zero = 0;
6315 spv::Id one = 0;
6316
6317 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6318
6319 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006320 case glslang::EOpConvIntToBool:
6321 case glslang::EOpConvUintToBool:
6322 zero = builder.makeUintConstant(0);
6323 zero = makeSmearedConstant(zero, vectorSize);
6324 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006325 case glslang::EOpConvFloatToBool:
6326 zero = builder.makeFloatConstant(0.0F);
6327 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006328 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006329 case glslang::EOpConvBoolToFloat:
6330 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006331 zero = builder.makeFloatConstant(0.0F);
6332 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006333 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006334
John Kessenich140f3df2015-06-26 16:58:36 -06006335 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006336 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006337#ifndef GLSLANG_WEB
6338 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006339 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006340 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006341 } else
6342#endif
6343 {
6344 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006345 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006346 }
Rex Xucabbb782017-03-24 13:41:14 +08006347
John Kessenich140f3df2015-06-26 16:58:36 -06006348 convOp = spv::OpSelect;
6349 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006350
John Kessenich140f3df2015-06-26 16:58:36 -06006351 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006352 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006353#ifndef GLSLANG_WEB
6354 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006355 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006356 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006357 } else
6358#endif
6359 {
6360 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006361 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006362 }
Rex Xucabbb782017-03-24 13:41:14 +08006363
John Kessenich140f3df2015-06-26 16:58:36 -06006364 convOp = spv::OpSelect;
6365 break;
6366
John Kessenich66011cb2018-03-06 16:12:04 -07006367 case glslang::EOpConvInt8ToFloat16:
6368 case glslang::EOpConvInt8ToFloat:
6369 case glslang::EOpConvInt8ToDouble:
6370 case glslang::EOpConvInt16ToFloat16:
6371 case glslang::EOpConvInt16ToFloat:
6372 case glslang::EOpConvInt16ToDouble:
6373 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006374 case glslang::EOpConvIntToFloat:
6375 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006376 case glslang::EOpConvInt64ToFloat:
6377 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006378 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006379 convOp = spv::OpConvertSToF;
6380 break;
6381
John Kessenich66011cb2018-03-06 16:12:04 -07006382 case glslang::EOpConvUint8ToFloat16:
6383 case glslang::EOpConvUint8ToFloat:
6384 case glslang::EOpConvUint8ToDouble:
6385 case glslang::EOpConvUint16ToFloat16:
6386 case glslang::EOpConvUint16ToFloat:
6387 case glslang::EOpConvUint16ToDouble:
6388 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006389 case glslang::EOpConvUintToFloat:
6390 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006391 case glslang::EOpConvUint64ToFloat:
6392 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006393 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006394 convOp = spv::OpConvertUToF;
6395 break;
6396
John Kessenich66011cb2018-03-06 16:12:04 -07006397 case glslang::EOpConvFloat16ToInt8:
6398 case glslang::EOpConvFloatToInt8:
6399 case glslang::EOpConvDoubleToInt8:
6400 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006401 case glslang::EOpConvFloatToInt16:
6402 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006403 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006404 case glslang::EOpConvFloatToInt:
6405 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006406 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006407 case glslang::EOpConvFloatToInt64:
6408 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006409 convOp = spv::OpConvertFToS;
6410 break;
6411
John Kessenich66011cb2018-03-06 16:12:04 -07006412 case glslang::EOpConvUint8ToInt8:
6413 case glslang::EOpConvInt8ToUint8:
6414 case glslang::EOpConvUint16ToInt16:
6415 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006416 case glslang::EOpConvUintToInt:
6417 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006418 case glslang::EOpConvUint64ToInt64:
6419 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006420 if (builder.isInSpecConstCodeGenMode()) {
6421 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006422#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006423 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6424 zero = builder.makeUint8Constant(0);
6425 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006426 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006427 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6428 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006429 } else
6430#endif
6431 {
Rex Xucabbb782017-03-24 13:41:14 +08006432 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006433 }
qining189b2032016-04-12 23:16:20 -04006434 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006435 // Use OpIAdd, instead of OpBitcast to do the conversion when
6436 // generating for OpSpecConstantOp instruction.
6437 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6438 }
6439 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006440 convOp = spv::OpBitcast;
6441 break;
6442
John Kessenich66011cb2018-03-06 16:12:04 -07006443 case glslang::EOpConvFloat16ToUint8:
6444 case glslang::EOpConvFloatToUint8:
6445 case glslang::EOpConvDoubleToUint8:
6446 case glslang::EOpConvFloat16ToUint16:
6447 case glslang::EOpConvFloatToUint16:
6448 case glslang::EOpConvDoubleToUint16:
6449 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006450 case glslang::EOpConvFloatToUint:
6451 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006452 case glslang::EOpConvFloatToUint64:
6453 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006454 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006455 convOp = spv::OpConvertFToU;
6456 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006457
John Kessenich39697cd2019-08-08 10:35:51 -06006458#ifndef GLSLANG_WEB
6459 case glslang::EOpConvInt8ToBool:
6460 case glslang::EOpConvUint8ToBool:
6461 zero = builder.makeUint8Constant(0);
6462 zero = makeSmearedConstant(zero, vectorSize);
6463 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6464 case glslang::EOpConvInt16ToBool:
6465 case glslang::EOpConvUint16ToBool:
6466 zero = builder.makeUint16Constant(0);
6467 zero = makeSmearedConstant(zero, vectorSize);
6468 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6469 case glslang::EOpConvInt64ToBool:
6470 case glslang::EOpConvUint64ToBool:
6471 zero = builder.makeUint64Constant(0);
6472 zero = makeSmearedConstant(zero, vectorSize);
6473 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6474 case glslang::EOpConvDoubleToBool:
6475 zero = builder.makeDoubleConstant(0.0);
6476 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006477 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006478 case glslang::EOpConvFloat16ToBool:
6479 zero = builder.makeFloat16Constant(0.0F);
6480 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006481 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006482 case glslang::EOpConvBoolToDouble:
6483 convOp = spv::OpSelect;
6484 zero = builder.makeDoubleConstant(0.0);
6485 one = builder.makeDoubleConstant(1.0);
6486 break;
6487 case glslang::EOpConvBoolToFloat16:
6488 convOp = spv::OpSelect;
6489 zero = builder.makeFloat16Constant(0.0F);
6490 one = builder.makeFloat16Constant(1.0F);
6491 break;
6492 case glslang::EOpConvBoolToInt8:
6493 zero = builder.makeInt8Constant(0);
6494 one = builder.makeInt8Constant(1);
6495 convOp = spv::OpSelect;
6496 break;
6497 case glslang::EOpConvBoolToUint8:
6498 zero = builder.makeUint8Constant(0);
6499 one = builder.makeUint8Constant(1);
6500 convOp = spv::OpSelect;
6501 break;
6502 case glslang::EOpConvBoolToInt16:
6503 zero = builder.makeInt16Constant(0);
6504 one = builder.makeInt16Constant(1);
6505 convOp = spv::OpSelect;
6506 break;
6507 case glslang::EOpConvBoolToUint16:
6508 zero = builder.makeUint16Constant(0);
6509 one = builder.makeUint16Constant(1);
6510 convOp = spv::OpSelect;
6511 break;
6512 case glslang::EOpConvDoubleToFloat:
6513 case glslang::EOpConvFloatToDouble:
6514 case glslang::EOpConvDoubleToFloat16:
6515 case glslang::EOpConvFloat16ToDouble:
6516 case glslang::EOpConvFloatToFloat16:
6517 case glslang::EOpConvFloat16ToFloat:
6518 convOp = spv::OpFConvert;
6519 if (builder.isMatrixType(destType))
6520 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6521 break;
6522
John Kessenich66011cb2018-03-06 16:12:04 -07006523 case glslang::EOpConvInt8ToInt16:
6524 case glslang::EOpConvInt8ToInt:
6525 case glslang::EOpConvInt8ToInt64:
6526 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006527 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006528 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006529 case glslang::EOpConvIntToInt8:
6530 case glslang::EOpConvIntToInt16:
6531 case glslang::EOpConvIntToInt64:
6532 case glslang::EOpConvInt64ToInt8:
6533 case glslang::EOpConvInt64ToInt16:
6534 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006535 convOp = spv::OpSConvert;
6536 break;
6537
John Kessenich66011cb2018-03-06 16:12:04 -07006538 case glslang::EOpConvUint8ToUint16:
6539 case glslang::EOpConvUint8ToUint:
6540 case glslang::EOpConvUint8ToUint64:
6541 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006542 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006543 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006544 case glslang::EOpConvUintToUint8:
6545 case glslang::EOpConvUintToUint16:
6546 case glslang::EOpConvUintToUint64:
6547 case glslang::EOpConvUint64ToUint8:
6548 case glslang::EOpConvUint64ToUint16:
6549 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006550 convOp = spv::OpUConvert;
6551 break;
6552
John Kessenich66011cb2018-03-06 16:12:04 -07006553 case glslang::EOpConvInt8ToUint16:
6554 case glslang::EOpConvInt8ToUint:
6555 case glslang::EOpConvInt8ToUint64:
6556 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006557 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006558 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006559 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006560 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006561 case glslang::EOpConvIntToUint64:
6562 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006563 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006564 case glslang::EOpConvInt64ToUint:
6565 case glslang::EOpConvUint8ToInt16:
6566 case glslang::EOpConvUint8ToInt:
6567 case glslang::EOpConvUint8ToInt64:
6568 case glslang::EOpConvUint16ToInt8:
6569 case glslang::EOpConvUint16ToInt:
6570 case glslang::EOpConvUint16ToInt64:
6571 case glslang::EOpConvUintToInt8:
6572 case glslang::EOpConvUintToInt16:
6573 case glslang::EOpConvUintToInt64:
6574 case glslang::EOpConvUint64ToInt8:
6575 case glslang::EOpConvUint64ToInt16:
6576 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006577 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006578 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006579
6580 if (builder.isInSpecConstCodeGenMode()) {
6581 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006582 switch(op) {
6583 case glslang::EOpConvInt16ToUint8:
6584 case glslang::EOpConvIntToUint8:
6585 case glslang::EOpConvInt64ToUint8:
6586 case glslang::EOpConvUint16ToInt8:
6587 case glslang::EOpConvUintToInt8:
6588 case glslang::EOpConvUint64ToInt8:
6589 zero = builder.makeUint8Constant(0);
6590 break;
6591 case glslang::EOpConvInt8ToUint16:
6592 case glslang::EOpConvIntToUint16:
6593 case glslang::EOpConvInt64ToUint16:
6594 case glslang::EOpConvUint8ToInt16:
6595 case glslang::EOpConvUintToInt16:
6596 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006597 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006598 break;
6599 case glslang::EOpConvInt8ToUint:
6600 case glslang::EOpConvInt16ToUint:
6601 case glslang::EOpConvInt64ToUint:
6602 case glslang::EOpConvUint8ToInt:
6603 case glslang::EOpConvUint16ToInt:
6604 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006605 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006606 break;
6607 case glslang::EOpConvInt8ToUint64:
6608 case glslang::EOpConvInt16ToUint64:
6609 case glslang::EOpConvIntToUint64:
6610 case glslang::EOpConvUint8ToInt64:
6611 case glslang::EOpConvUint16ToInt64:
6612 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006613 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006614 break;
6615 default:
6616 assert(false && "Default missing");
6617 break;
6618 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006619 zero = makeSmearedConstant(zero, vectorSize);
6620 // Use OpIAdd, instead of OpBitcast to do the conversion when
6621 // generating for OpSpecConstantOp instruction.
6622 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6623 }
6624 // For normal run-time conversion instruction, use OpBitcast.
6625 convOp = spv::OpBitcast;
6626 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006627 case glslang::EOpConvUint64ToPtr:
6628 convOp = spv::OpConvertUToPtr;
6629 break;
6630 case glslang::EOpConvPtrToUint64:
6631 convOp = spv::OpConvertPtrToU;
6632 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006633 case glslang::EOpConvPtrToUvec2:
6634 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006635 if (builder.isVector(operand))
6636 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6637 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006638 convOp = spv::OpBitcast;
6639 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006640#endif
6641
John Kessenich140f3df2015-06-26 16:58:36 -06006642 default:
6643 break;
6644 }
6645
6646 spv::Id result = 0;
6647 if (convOp == spv::OpNop)
6648 return result;
6649
6650 if (convOp == spv::OpSelect) {
6651 zero = makeSmearedConstant(zero, vectorSize);
6652 one = makeSmearedConstant(one, vectorSize);
6653 result = builder.createTriOp(convOp, destType, operand, one, zero);
6654 } else
6655 result = builder.createUnaryOp(convOp, destType, operand);
6656
John Kessenichead86222018-03-28 18:01:20 -06006657 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006658 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006659 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006660}
6661
6662spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6663{
6664 if (vectorSize == 0)
6665 return constant;
6666
6667 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6668 std::vector<spv::Id> components;
6669 for (int c = 0; c < vectorSize; ++c)
6670 components.push_back(constant);
6671 return builder.makeCompositeConstant(vectorTypeId, components);
6672}
6673
John Kessenich426394d2015-07-23 10:22:48 -06006674// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006675spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6676 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6677 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006678{
6679 spv::Op opCode = spv::OpNop;
6680
6681 switch (op) {
6682 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006683 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006684 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006685 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006686 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6687 opCode = spv::OpAtomicFAddEXT;
6688 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6689 if (typeProxy == glslang::EbtFloat)
6690 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6691 else
6692 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6693 }
John Kessenich426394d2015-07-23 10:22:48 -06006694 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006695 case glslang::EOpAtomicCounterSubtract:
6696 opCode = spv::OpAtomicISub;
6697 break;
John Kessenich426394d2015-07-23 10:22:48 -06006698 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006699 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006700 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006701 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6702 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006703 break;
6704 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006705 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006706 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006707 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6708 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006709 break;
6710 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006711 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006712 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006713 opCode = spv::OpAtomicAnd;
6714 break;
6715 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006716 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006717 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006718 opCode = spv::OpAtomicOr;
6719 break;
6720 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006721 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006722 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006723 opCode = spv::OpAtomicXor;
6724 break;
6725 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006726 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006727 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006728 opCode = spv::OpAtomicExchange;
6729 break;
6730 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006731 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006732 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006733 opCode = spv::OpAtomicCompareExchange;
6734 break;
6735 case glslang::EOpAtomicCounterIncrement:
6736 opCode = spv::OpAtomicIIncrement;
6737 break;
6738 case glslang::EOpAtomicCounterDecrement:
6739 opCode = spv::OpAtomicIDecrement;
6740 break;
6741 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006742 case glslang::EOpImageAtomicLoad:
6743 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006744 opCode = spv::OpAtomicLoad;
6745 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006746 case glslang::EOpAtomicStore:
6747 case glslang::EOpImageAtomicStore:
6748 opCode = spv::OpAtomicStore;
6749 break;
John Kessenich426394d2015-07-23 10:22:48 -06006750 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006751 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006752 break;
6753 }
6754
Rex Xue8fe8b02017-09-26 15:42:56 +08006755 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6756 builder.addCapability(spv::CapabilityInt64Atomics);
6757
John Kessenich426394d2015-07-23 10:22:48 -06006758 // Sort out the operands
6759 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006760 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006761 // - compare-exchange swaps the value and comparator
6762 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006763 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006764 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6765 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6766 spv::Id scopeId;
6767 if (glslangIntermediate->usingVulkanMemoryModel()) {
6768 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6769 } else {
6770 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6771 }
6772 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006773 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6774 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006775 spv::MemorySemanticsVolatileMask :
6776 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006777 spv::Id semanticsId2 = semanticsId;
6778
6779 pointerId = operands[0];
6780 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6781 // no additional operands
6782 } else if (opCode == spv::OpAtomicCompareExchange) {
6783 compareId = operands[1];
6784 valueId = operands[2];
6785 if (operands.size() > 3) {
6786 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006787 semanticsId = builder.makeUintConstant(
6788 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6789 semanticsId2 = builder.makeUintConstant(
6790 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006791 }
6792 } else if (opCode == spv::OpAtomicLoad) {
6793 if (operands.size() > 1) {
6794 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006795 semanticsId = builder.makeUintConstant(
6796 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006797 }
6798 } else {
6799 // atomic store or RMW
6800 valueId = operands[1];
6801 if (operands.size() > 2) {
6802 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006803 semanticsId = builder.makeUintConstant
6804 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006805 }
Rex Xu04db3f52015-09-16 11:44:02 +08006806 }
John Kessenich426394d2015-07-23 10:22:48 -06006807
Jeff Bolz36831c92018-09-05 10:11:41 -05006808 // Check for capabilities
6809 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006810 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6811 spv::MemorySemanticsMakeVisibleKHRMask |
6812 spv::MemorySemanticsOutputMemoryKHRMask |
6813 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006814 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6815 }
John Kessenich426394d2015-07-23 10:22:48 -06006816
Jeff Bolz36831c92018-09-05 10:11:41 -05006817 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6818 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6819 }
John Kessenich48d6e792017-10-06 21:21:48 -06006820
Jeff Bolz36831c92018-09-05 10:11:41 -05006821 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6822 spvAtomicOperands.push_back(pointerId);
6823 spvAtomicOperands.push_back(scopeId);
6824 spvAtomicOperands.push_back(semanticsId);
6825 if (opCode == spv::OpAtomicCompareExchange) {
6826 spvAtomicOperands.push_back(semanticsId2);
6827 spvAtomicOperands.push_back(valueId);
6828 spvAtomicOperands.push_back(compareId);
6829 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6830 spvAtomicOperands.push_back(valueId);
6831 }
John Kessenich48d6e792017-10-06 21:21:48 -06006832
Jeff Bolz36831c92018-09-05 10:11:41 -05006833 if (opCode == spv::OpAtomicStore) {
6834 builder.createNoResultOp(opCode, spvAtomicOperands);
6835 return 0;
6836 } else {
6837 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6838
6839 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6840 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6841 if (op == glslang::EOpAtomicCounterDecrement)
6842 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6843
6844 return resultId;
6845 }
John Kessenich426394d2015-07-23 10:22:48 -06006846}
6847
John Kessenich91cef522016-05-05 16:45:40 -06006848// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006849spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6850 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006851{
John Kessenich66011cb2018-03-06 16:12:04 -07006852 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6853 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006854
Rex Xu51596642016-09-21 18:56:12 +08006855 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006856 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006857 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6858
chaocf200da82016-12-20 12:44:35 -08006859 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6860 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006861 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6862 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006863 } else if (op == glslang::EOpAnyInvocation ||
6864 op == glslang::EOpAllInvocations ||
6865 op == glslang::EOpAllInvocationsEqual) {
6866 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6867 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006868 } else {
6869 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006870 if (op == glslang::EOpMinInvocationsNonUniform ||
6871 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006872 op == glslang::EOpAddInvocationsNonUniform ||
6873 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6874 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6875 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6876 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6877 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6878 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006879 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006880
Rex Xu430ef402016-10-14 17:22:23 +08006881 switch (op) {
6882 case glslang::EOpMinInvocations:
6883 case glslang::EOpMaxInvocations:
6884 case glslang::EOpAddInvocations:
6885 case glslang::EOpMinInvocationsNonUniform:
6886 case glslang::EOpMaxInvocationsNonUniform:
6887 case glslang::EOpAddInvocationsNonUniform:
6888 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006889 break;
6890 case glslang::EOpMinInvocationsInclusiveScan:
6891 case glslang::EOpMaxInvocationsInclusiveScan:
6892 case glslang::EOpAddInvocationsInclusiveScan:
6893 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6894 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6895 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6896 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006897 break;
6898 case glslang::EOpMinInvocationsExclusiveScan:
6899 case glslang::EOpMaxInvocationsExclusiveScan:
6900 case glslang::EOpAddInvocationsExclusiveScan:
6901 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6902 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6903 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6904 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006905 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006906 default:
6907 break;
Rex Xu430ef402016-10-14 17:22:23 +08006908 }
John Kessenich149afc32018-08-14 13:31:43 -06006909 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6910 spvGroupOperands.push_back(scope);
6911 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006912 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006913 spvGroupOperands.push_back(groupOp);
6914 }
Rex Xu51596642016-09-21 18:56:12 +08006915 }
6916
John Kessenich149afc32018-08-14 13:31:43 -06006917 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6918 spv::IdImmediate op = { true, *opIt };
6919 spvGroupOperands.push_back(op);
6920 }
John Kessenich91cef522016-05-05 16:45:40 -06006921
6922 switch (op) {
6923 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006924 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006925 break;
John Kessenich91cef522016-05-05 16:45:40 -06006926 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006927 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006928 break;
John Kessenich91cef522016-05-05 16:45:40 -06006929 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006930 opCode = spv::OpSubgroupAllEqualKHR;
6931 break;
Rex Xu51596642016-09-21 18:56:12 +08006932 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006933 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006934 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006935 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006936 break;
6937 case glslang::EOpReadFirstInvocation:
6938 opCode = spv::OpSubgroupFirstInvocationKHR;
6939 break;
6940 case glslang::EOpBallot:
6941 {
6942 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6943 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6944 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6945 //
6946 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6947 //
6948 spv::Id uintType = builder.makeUintType(32);
6949 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6950 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6951
6952 std::vector<spv::Id> components;
6953 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6954 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6955
6956 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6957 return builder.createUnaryOp(spv::OpBitcast, typeId,
6958 builder.createCompositeConstruct(uvec2Type, components));
6959 }
6960
Rex Xu9d93a232016-05-05 12:30:44 +08006961 case glslang::EOpMinInvocations:
6962 case glslang::EOpMaxInvocations:
6963 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006964 case glslang::EOpMinInvocationsInclusiveScan:
6965 case glslang::EOpMaxInvocationsInclusiveScan:
6966 case glslang::EOpAddInvocationsInclusiveScan:
6967 case glslang::EOpMinInvocationsExclusiveScan:
6968 case glslang::EOpMaxInvocationsExclusiveScan:
6969 case glslang::EOpAddInvocationsExclusiveScan:
6970 if (op == glslang::EOpMinInvocations ||
6971 op == glslang::EOpMinInvocationsInclusiveScan ||
6972 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006973 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006974 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006975 else {
6976 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006977 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006978 else
Rex Xu51596642016-09-21 18:56:12 +08006979 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006980 }
Rex Xu430ef402016-10-14 17:22:23 +08006981 } else if (op == glslang::EOpMaxInvocations ||
6982 op == glslang::EOpMaxInvocationsInclusiveScan ||
6983 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006984 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006985 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006986 else {
6987 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006988 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006989 else
Rex Xu51596642016-09-21 18:56:12 +08006990 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006991 }
6992 } else {
6993 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006994 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006995 else
Rex Xu51596642016-09-21 18:56:12 +08006996 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006997 }
6998
Rex Xu2bbbe062016-08-23 15:41:05 +08006999 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007000 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007001
7002 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007003 case glslang::EOpMinInvocationsNonUniform:
7004 case glslang::EOpMaxInvocationsNonUniform:
7005 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007006 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7007 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7008 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7009 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7010 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7011 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7012 if (op == glslang::EOpMinInvocationsNonUniform ||
7013 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7014 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007015 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007016 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007017 else {
7018 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007019 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007020 else
Rex Xu51596642016-09-21 18:56:12 +08007021 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007022 }
7023 }
Rex Xu430ef402016-10-14 17:22:23 +08007024 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7025 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7026 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007027 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007028 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007029 else {
7030 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007031 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007032 else
Rex Xu51596642016-09-21 18:56:12 +08007033 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007034 }
7035 }
7036 else {
7037 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007038 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007039 else
Rex Xu51596642016-09-21 18:56:12 +08007040 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007041 }
7042
Rex Xu2bbbe062016-08-23 15:41:05 +08007043 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007044 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007045
7046 break;
John Kessenich91cef522016-05-05 16:45:40 -06007047 default:
7048 logger->missingFunctionality("invocation operation");
7049 return spv::NoResult;
7050 }
Rex Xu51596642016-09-21 18:56:12 +08007051
7052 assert(opCode != spv::OpNop);
7053 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007054}
7055
Rex Xu2bbbe062016-08-23 15:41:05 +08007056// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007057spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7058 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007059{
7060 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7061 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007062 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007063 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007064 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7065 op == spv::OpGroupSMinNonUniformAMD ||
7066 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7067 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007068 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7069
7070 // Handle group invocation operations scalar by scalar.
7071 // The result type is the same type as the original type.
7072 // The algorithm is to:
7073 // - break the vector into scalars
7074 // - apply the operation to each scalar
7075 // - make a vector out the scalar results
7076
7077 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007078 int numComponents = builder.getNumComponents(operands[0]);
7079 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007080 std::vector<spv::Id> results;
7081
7082 // do each scalar op
7083 for (int comp = 0; comp < numComponents; ++comp) {
7084 std::vector<unsigned int> indexes;
7085 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007086 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7087 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007088 if (op == spv::OpSubgroupReadInvocationKHR) {
7089 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007090 spv::IdImmediate operand = { true, operands[1] };
7091 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007092 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007093 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7094 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007095 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007096 spv::IdImmediate operand = { true, operands[1] };
7097 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007098 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007099 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7100 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007101 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007102 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007103 spvGroupOperands.push_back(scalar);
7104 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007105
Rex Xub7072052016-09-26 15:53:40 +08007106 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007107 }
7108
7109 // put the pieces together
7110 return builder.createCompositeConstruct(typeId, results);
7111}
Rex Xu2bbbe062016-08-23 15:41:05 +08007112
John Kessenich66011cb2018-03-06 16:12:04 -07007113// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007114spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7115 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007116{
7117 // Add the required capabilities.
7118 switch (op) {
7119 case glslang::EOpSubgroupElect:
7120 builder.addCapability(spv::CapabilityGroupNonUniform);
7121 break;
7122 case glslang::EOpSubgroupAll:
7123 case glslang::EOpSubgroupAny:
7124 case glslang::EOpSubgroupAllEqual:
7125 builder.addCapability(spv::CapabilityGroupNonUniform);
7126 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7127 break;
7128 case glslang::EOpSubgroupBroadcast:
7129 case glslang::EOpSubgroupBroadcastFirst:
7130 case glslang::EOpSubgroupBallot:
7131 case glslang::EOpSubgroupInverseBallot:
7132 case glslang::EOpSubgroupBallotBitExtract:
7133 case glslang::EOpSubgroupBallotBitCount:
7134 case glslang::EOpSubgroupBallotInclusiveBitCount:
7135 case glslang::EOpSubgroupBallotExclusiveBitCount:
7136 case glslang::EOpSubgroupBallotFindLSB:
7137 case glslang::EOpSubgroupBallotFindMSB:
7138 builder.addCapability(spv::CapabilityGroupNonUniform);
7139 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7140 break;
7141 case glslang::EOpSubgroupShuffle:
7142 case glslang::EOpSubgroupShuffleXor:
7143 builder.addCapability(spv::CapabilityGroupNonUniform);
7144 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7145 break;
7146 case glslang::EOpSubgroupShuffleUp:
7147 case glslang::EOpSubgroupShuffleDown:
7148 builder.addCapability(spv::CapabilityGroupNonUniform);
7149 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7150 break;
7151 case glslang::EOpSubgroupAdd:
7152 case glslang::EOpSubgroupMul:
7153 case glslang::EOpSubgroupMin:
7154 case glslang::EOpSubgroupMax:
7155 case glslang::EOpSubgroupAnd:
7156 case glslang::EOpSubgroupOr:
7157 case glslang::EOpSubgroupXor:
7158 case glslang::EOpSubgroupInclusiveAdd:
7159 case glslang::EOpSubgroupInclusiveMul:
7160 case glslang::EOpSubgroupInclusiveMin:
7161 case glslang::EOpSubgroupInclusiveMax:
7162 case glslang::EOpSubgroupInclusiveAnd:
7163 case glslang::EOpSubgroupInclusiveOr:
7164 case glslang::EOpSubgroupInclusiveXor:
7165 case glslang::EOpSubgroupExclusiveAdd:
7166 case glslang::EOpSubgroupExclusiveMul:
7167 case glslang::EOpSubgroupExclusiveMin:
7168 case glslang::EOpSubgroupExclusiveMax:
7169 case glslang::EOpSubgroupExclusiveAnd:
7170 case glslang::EOpSubgroupExclusiveOr:
7171 case glslang::EOpSubgroupExclusiveXor:
7172 builder.addCapability(spv::CapabilityGroupNonUniform);
7173 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7174 break;
7175 case glslang::EOpSubgroupClusteredAdd:
7176 case glslang::EOpSubgroupClusteredMul:
7177 case glslang::EOpSubgroupClusteredMin:
7178 case glslang::EOpSubgroupClusteredMax:
7179 case glslang::EOpSubgroupClusteredAnd:
7180 case glslang::EOpSubgroupClusteredOr:
7181 case glslang::EOpSubgroupClusteredXor:
7182 builder.addCapability(spv::CapabilityGroupNonUniform);
7183 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7184 break;
7185 case glslang::EOpSubgroupQuadBroadcast:
7186 case glslang::EOpSubgroupQuadSwapHorizontal:
7187 case glslang::EOpSubgroupQuadSwapVertical:
7188 case glslang::EOpSubgroupQuadSwapDiagonal:
7189 builder.addCapability(spv::CapabilityGroupNonUniform);
7190 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7191 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007192 case glslang::EOpSubgroupPartitionedAdd:
7193 case glslang::EOpSubgroupPartitionedMul:
7194 case glslang::EOpSubgroupPartitionedMin:
7195 case glslang::EOpSubgroupPartitionedMax:
7196 case glslang::EOpSubgroupPartitionedAnd:
7197 case glslang::EOpSubgroupPartitionedOr:
7198 case glslang::EOpSubgroupPartitionedXor:
7199 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7200 case glslang::EOpSubgroupPartitionedInclusiveMul:
7201 case glslang::EOpSubgroupPartitionedInclusiveMin:
7202 case glslang::EOpSubgroupPartitionedInclusiveMax:
7203 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7204 case glslang::EOpSubgroupPartitionedInclusiveOr:
7205 case glslang::EOpSubgroupPartitionedInclusiveXor:
7206 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7207 case glslang::EOpSubgroupPartitionedExclusiveMul:
7208 case glslang::EOpSubgroupPartitionedExclusiveMin:
7209 case glslang::EOpSubgroupPartitionedExclusiveMax:
7210 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7211 case glslang::EOpSubgroupPartitionedExclusiveOr:
7212 case glslang::EOpSubgroupPartitionedExclusiveXor:
7213 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7214 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7215 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007216 default: assert(0 && "Unhandled subgroup operation!");
7217 }
7218
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007219
7220 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7221 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007222 const bool isBool = typeProxy == glslang::EbtBool;
7223
7224 spv::Op opCode = spv::OpNop;
7225
7226 // Figure out which opcode to use.
7227 switch (op) {
7228 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7229 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7230 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7231 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7232 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7233 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7234 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7235 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7236 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7237 case glslang::EOpSubgroupBallotBitCount:
7238 case glslang::EOpSubgroupBallotInclusiveBitCount:
7239 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7240 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7241 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7242 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7243 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7244 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7245 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7246 case glslang::EOpSubgroupAdd:
7247 case glslang::EOpSubgroupInclusiveAdd:
7248 case glslang::EOpSubgroupExclusiveAdd:
7249 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007250 case glslang::EOpSubgroupPartitionedAdd:
7251 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7252 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007253 if (isFloat) {
7254 opCode = spv::OpGroupNonUniformFAdd;
7255 } else {
7256 opCode = spv::OpGroupNonUniformIAdd;
7257 }
7258 break;
7259 case glslang::EOpSubgroupMul:
7260 case glslang::EOpSubgroupInclusiveMul:
7261 case glslang::EOpSubgroupExclusiveMul:
7262 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007263 case glslang::EOpSubgroupPartitionedMul:
7264 case glslang::EOpSubgroupPartitionedInclusiveMul:
7265 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007266 if (isFloat) {
7267 opCode = spv::OpGroupNonUniformFMul;
7268 } else {
7269 opCode = spv::OpGroupNonUniformIMul;
7270 }
7271 break;
7272 case glslang::EOpSubgroupMin:
7273 case glslang::EOpSubgroupInclusiveMin:
7274 case glslang::EOpSubgroupExclusiveMin:
7275 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007276 case glslang::EOpSubgroupPartitionedMin:
7277 case glslang::EOpSubgroupPartitionedInclusiveMin:
7278 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007279 if (isFloat) {
7280 opCode = spv::OpGroupNonUniformFMin;
7281 } else if (isUnsigned) {
7282 opCode = spv::OpGroupNonUniformUMin;
7283 } else {
7284 opCode = spv::OpGroupNonUniformSMin;
7285 }
7286 break;
7287 case glslang::EOpSubgroupMax:
7288 case glslang::EOpSubgroupInclusiveMax:
7289 case glslang::EOpSubgroupExclusiveMax:
7290 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007291 case glslang::EOpSubgroupPartitionedMax:
7292 case glslang::EOpSubgroupPartitionedInclusiveMax:
7293 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007294 if (isFloat) {
7295 opCode = spv::OpGroupNonUniformFMax;
7296 } else if (isUnsigned) {
7297 opCode = spv::OpGroupNonUniformUMax;
7298 } else {
7299 opCode = spv::OpGroupNonUniformSMax;
7300 }
7301 break;
7302 case glslang::EOpSubgroupAnd:
7303 case glslang::EOpSubgroupInclusiveAnd:
7304 case glslang::EOpSubgroupExclusiveAnd:
7305 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007306 case glslang::EOpSubgroupPartitionedAnd:
7307 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7308 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007309 if (isBool) {
7310 opCode = spv::OpGroupNonUniformLogicalAnd;
7311 } else {
7312 opCode = spv::OpGroupNonUniformBitwiseAnd;
7313 }
7314 break;
7315 case glslang::EOpSubgroupOr:
7316 case glslang::EOpSubgroupInclusiveOr:
7317 case glslang::EOpSubgroupExclusiveOr:
7318 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007319 case glslang::EOpSubgroupPartitionedOr:
7320 case glslang::EOpSubgroupPartitionedInclusiveOr:
7321 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007322 if (isBool) {
7323 opCode = spv::OpGroupNonUniformLogicalOr;
7324 } else {
7325 opCode = spv::OpGroupNonUniformBitwiseOr;
7326 }
7327 break;
7328 case glslang::EOpSubgroupXor:
7329 case glslang::EOpSubgroupInclusiveXor:
7330 case glslang::EOpSubgroupExclusiveXor:
7331 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007332 case glslang::EOpSubgroupPartitionedXor:
7333 case glslang::EOpSubgroupPartitionedInclusiveXor:
7334 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007335 if (isBool) {
7336 opCode = spv::OpGroupNonUniformLogicalXor;
7337 } else {
7338 opCode = spv::OpGroupNonUniformBitwiseXor;
7339 }
7340 break;
7341 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7342 case glslang::EOpSubgroupQuadSwapHorizontal:
7343 case glslang::EOpSubgroupQuadSwapVertical:
7344 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7345 default: assert(0 && "Unhandled subgroup operation!");
7346 }
7347
John Kessenich149afc32018-08-14 13:31:43 -06007348 // get the right Group Operation
7349 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007350 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007351 default:
7352 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007353 case glslang::EOpSubgroupBallotBitCount:
7354 case glslang::EOpSubgroupAdd:
7355 case glslang::EOpSubgroupMul:
7356 case glslang::EOpSubgroupMin:
7357 case glslang::EOpSubgroupMax:
7358 case glslang::EOpSubgroupAnd:
7359 case glslang::EOpSubgroupOr:
7360 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007361 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007362 break;
7363 case glslang::EOpSubgroupBallotInclusiveBitCount:
7364 case glslang::EOpSubgroupInclusiveAdd:
7365 case glslang::EOpSubgroupInclusiveMul:
7366 case glslang::EOpSubgroupInclusiveMin:
7367 case glslang::EOpSubgroupInclusiveMax:
7368 case glslang::EOpSubgroupInclusiveAnd:
7369 case glslang::EOpSubgroupInclusiveOr:
7370 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007371 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007372 break;
7373 case glslang::EOpSubgroupBallotExclusiveBitCount:
7374 case glslang::EOpSubgroupExclusiveAdd:
7375 case glslang::EOpSubgroupExclusiveMul:
7376 case glslang::EOpSubgroupExclusiveMin:
7377 case glslang::EOpSubgroupExclusiveMax:
7378 case glslang::EOpSubgroupExclusiveAnd:
7379 case glslang::EOpSubgroupExclusiveOr:
7380 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007381 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007382 break;
7383 case glslang::EOpSubgroupClusteredAdd:
7384 case glslang::EOpSubgroupClusteredMul:
7385 case glslang::EOpSubgroupClusteredMin:
7386 case glslang::EOpSubgroupClusteredMax:
7387 case glslang::EOpSubgroupClusteredAnd:
7388 case glslang::EOpSubgroupClusteredOr:
7389 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007390 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007391 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007392 case glslang::EOpSubgroupPartitionedAdd:
7393 case glslang::EOpSubgroupPartitionedMul:
7394 case glslang::EOpSubgroupPartitionedMin:
7395 case glslang::EOpSubgroupPartitionedMax:
7396 case glslang::EOpSubgroupPartitionedAnd:
7397 case glslang::EOpSubgroupPartitionedOr:
7398 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007399 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007400 break;
7401 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7402 case glslang::EOpSubgroupPartitionedInclusiveMul:
7403 case glslang::EOpSubgroupPartitionedInclusiveMin:
7404 case glslang::EOpSubgroupPartitionedInclusiveMax:
7405 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7406 case glslang::EOpSubgroupPartitionedInclusiveOr:
7407 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007408 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007409 break;
7410 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7411 case glslang::EOpSubgroupPartitionedExclusiveMul:
7412 case glslang::EOpSubgroupPartitionedExclusiveMin:
7413 case glslang::EOpSubgroupPartitionedExclusiveMax:
7414 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7415 case glslang::EOpSubgroupPartitionedExclusiveOr:
7416 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007417 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007418 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007419 }
7420
John Kessenich149afc32018-08-14 13:31:43 -06007421 // build the instruction
7422 std::vector<spv::IdImmediate> spvGroupOperands;
7423
7424 // Every operation begins with the Execution Scope operand.
7425 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7426 spvGroupOperands.push_back(executionScope);
7427
7428 // Next, for all operations that use a Group Operation, push that as an operand.
7429 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007430 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007431 spvGroupOperands.push_back(groupOperand);
7432 }
7433
John Kessenich66011cb2018-03-06 16:12:04 -07007434 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007435 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7436 spv::IdImmediate operand = { true, *opIt };
7437 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007438 }
7439
7440 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007441 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007442 switch (op) {
7443 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007444 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7445 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7446 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7447 }
7448 if (directionId != spv::NoResult) {
7449 spv::IdImmediate direction = { true, directionId };
7450 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007451 }
7452
7453 return builder.createOp(opCode, typeId, spvGroupOperands);
7454}
7455
John Kessenich8985fc92020-03-03 10:25:07 -07007456spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7457 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007458{
John Kessenich66011cb2018-03-06 16:12:04 -07007459 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7460 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007461
John Kessenich140f3df2015-06-26 16:58:36 -06007462 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007463 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007464 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007465 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007466 spv::Id typeId0 = 0;
7467 if (consumedOperands > 0)
7468 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007469 spv::Id typeId1 = 0;
7470 if (consumedOperands > 1)
7471 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007472 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007473
7474 switch (op) {
7475 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007476 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007477 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007478 else if (isUnsigned)
7479 libCall = spv::GLSLstd450UMin;
7480 else
7481 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007482 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007483 break;
7484 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007485 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007486 break;
7487 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007488 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007489 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007490 else if (isUnsigned)
7491 libCall = spv::GLSLstd450UMax;
7492 else
7493 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007494 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007495 break;
7496 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007497 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007498 break;
7499 case glslang::EOpDot:
7500 opCode = spv::OpDot;
7501 break;
7502 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007503 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007504 break;
7505
7506 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007507 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007508 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007509 else if (isUnsigned)
7510 libCall = spv::GLSLstd450UClamp;
7511 else
7512 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007513 builder.promoteScalar(precision, operands.front(), operands[1]);
7514 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007515 break;
7516 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007517 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7518 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007519 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007520 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007521 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007522 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007523 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007524 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007525 break;
7526 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007527 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007528 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007529 break;
7530 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007531 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007532 builder.promoteScalar(precision, operands[0], operands[2]);
7533 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007534 break;
7535
7536 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007537 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007538 break;
7539 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007540 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007541 break;
7542 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007543 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007544 break;
7545 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007546 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007547 break;
7548 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007549 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007550 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007551 case glslang::EOpBarrier:
7552 {
7553 // This is for the extended controlBarrier function, with four operands.
7554 // The unextended barrier() goes through createNoArgOperation.
7555 assert(operands.size() == 4);
7556 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7557 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7558 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007559 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7560 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007561 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7562 spv::MemorySemanticsMakeVisibleKHRMask |
7563 spv::MemorySemanticsOutputMemoryKHRMask |
7564 spv::MemorySemanticsVolatileMask)) {
7565 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7566 }
John Kessenich8985fc92020-03-03 10:25:07 -07007567 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7568 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007569 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7570 }
7571 return 0;
7572 }
7573 break;
7574 case glslang::EOpMemoryBarrier:
7575 {
7576 // This is for the extended memoryBarrier function, with three operands.
7577 // The unextended memoryBarrier() goes through createNoArgOperation.
7578 assert(operands.size() == 3);
7579 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7580 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7581 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7582 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7583 spv::MemorySemanticsMakeVisibleKHRMask |
7584 spv::MemorySemanticsOutputMemoryKHRMask |
7585 spv::MemorySemanticsVolatileMask)) {
7586 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7587 }
7588 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7589 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7590 }
7591 return 0;
7592 }
7593 break;
7594
John Kessenicha28f7a72019-08-06 07:00:58 -06007595#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007596 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007597 if (typeProxy == glslang::EbtFloat16)
7598 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007599 libCall = spv::GLSLstd450InterpolateAtSample;
7600 break;
7601 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007602 if (typeProxy == glslang::EbtFloat16)
7603 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007604 libCall = spv::GLSLstd450InterpolateAtOffset;
7605 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007606 case glslang::EOpAddCarry:
7607 opCode = spv::OpIAddCarry;
7608 typeId = builder.makeStructResultType(typeId0, typeId0);
7609 consumedOperands = 2;
7610 break;
7611 case glslang::EOpSubBorrow:
7612 opCode = spv::OpISubBorrow;
7613 typeId = builder.makeStructResultType(typeId0, typeId0);
7614 consumedOperands = 2;
7615 break;
7616 case glslang::EOpUMulExtended:
7617 opCode = spv::OpUMulExtended;
7618 typeId = builder.makeStructResultType(typeId0, typeId0);
7619 consumedOperands = 2;
7620 break;
7621 case glslang::EOpIMulExtended:
7622 opCode = spv::OpSMulExtended;
7623 typeId = builder.makeStructResultType(typeId0, typeId0);
7624 consumedOperands = 2;
7625 break;
7626 case glslang::EOpBitfieldExtract:
7627 if (isUnsigned)
7628 opCode = spv::OpBitFieldUExtract;
7629 else
7630 opCode = spv::OpBitFieldSExtract;
7631 break;
7632 case glslang::EOpBitfieldInsert:
7633 opCode = spv::OpBitFieldInsert;
7634 break;
7635
7636 case glslang::EOpFma:
7637 libCall = spv::GLSLstd450Fma;
7638 break;
7639 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007640 {
7641 libCall = spv::GLSLstd450FrexpStruct;
7642 assert(builder.isPointerType(typeId1));
7643 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007644 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007645 if (width == 16)
7646 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7647 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007648 if (builder.getNumComponents(operands[0]) == 1)
7649 frexpIntType = builder.makeIntegerType(width, true);
7650 else
John Kessenich8985fc92020-03-03 10:25:07 -07007651 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7652 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007653 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7654 consumedOperands = 1;
7655 }
John Kessenich55e7d112015-11-15 21:33:39 -07007656 break;
7657 case glslang::EOpLdexp:
7658 libCall = spv::GLSLstd450Ldexp;
7659 break;
7660
Rex Xu574ab042016-04-14 16:53:07 +08007661 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007662 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007663
John Kessenich66011cb2018-03-06 16:12:04 -07007664 case glslang::EOpSubgroupBroadcast:
7665 case glslang::EOpSubgroupBallotBitExtract:
7666 case glslang::EOpSubgroupShuffle:
7667 case glslang::EOpSubgroupShuffleXor:
7668 case glslang::EOpSubgroupShuffleUp:
7669 case glslang::EOpSubgroupShuffleDown:
7670 case glslang::EOpSubgroupClusteredAdd:
7671 case glslang::EOpSubgroupClusteredMul:
7672 case glslang::EOpSubgroupClusteredMin:
7673 case glslang::EOpSubgroupClusteredMax:
7674 case glslang::EOpSubgroupClusteredAnd:
7675 case glslang::EOpSubgroupClusteredOr:
7676 case glslang::EOpSubgroupClusteredXor:
7677 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007678 case glslang::EOpSubgroupPartitionedAdd:
7679 case glslang::EOpSubgroupPartitionedMul:
7680 case glslang::EOpSubgroupPartitionedMin:
7681 case glslang::EOpSubgroupPartitionedMax:
7682 case glslang::EOpSubgroupPartitionedAnd:
7683 case glslang::EOpSubgroupPartitionedOr:
7684 case glslang::EOpSubgroupPartitionedXor:
7685 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7686 case glslang::EOpSubgroupPartitionedInclusiveMul:
7687 case glslang::EOpSubgroupPartitionedInclusiveMin:
7688 case glslang::EOpSubgroupPartitionedInclusiveMax:
7689 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7690 case glslang::EOpSubgroupPartitionedInclusiveOr:
7691 case glslang::EOpSubgroupPartitionedInclusiveXor:
7692 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7693 case glslang::EOpSubgroupPartitionedExclusiveMul:
7694 case glslang::EOpSubgroupPartitionedExclusiveMin:
7695 case glslang::EOpSubgroupPartitionedExclusiveMax:
7696 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7697 case glslang::EOpSubgroupPartitionedExclusiveOr:
7698 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007699 return createSubgroupOperation(op, typeId, operands, typeProxy);
7700
Rex Xu9d93a232016-05-05 12:30:44 +08007701 case glslang::EOpSwizzleInvocations:
7702 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7703 libCall = spv::SwizzleInvocationsAMD;
7704 break;
7705 case glslang::EOpSwizzleInvocationsMasked:
7706 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7707 libCall = spv::SwizzleInvocationsMaskedAMD;
7708 break;
7709 case glslang::EOpWriteInvocation:
7710 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7711 libCall = spv::WriteInvocationAMD;
7712 break;
7713
7714 case glslang::EOpMin3:
7715 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7716 if (isFloat)
7717 libCall = spv::FMin3AMD;
7718 else {
7719 if (isUnsigned)
7720 libCall = spv::UMin3AMD;
7721 else
7722 libCall = spv::SMin3AMD;
7723 }
7724 break;
7725 case glslang::EOpMax3:
7726 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7727 if (isFloat)
7728 libCall = spv::FMax3AMD;
7729 else {
7730 if (isUnsigned)
7731 libCall = spv::UMax3AMD;
7732 else
7733 libCall = spv::SMax3AMD;
7734 }
7735 break;
7736 case glslang::EOpMid3:
7737 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7738 if (isFloat)
7739 libCall = spv::FMid3AMD;
7740 else {
7741 if (isUnsigned)
7742 libCall = spv::UMid3AMD;
7743 else
7744 libCall = spv::SMid3AMD;
7745 }
7746 break;
7747
7748 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007749 if (typeProxy == glslang::EbtFloat16)
7750 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007751 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7752 libCall = spv::InterpolateAtVertexAMD;
7753 break;
Chao Chen3c366992018-09-19 11:41:59 -07007754
Daniel Kochdb32b242020-03-17 20:42:47 -04007755 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007756 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007757 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007758 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007759 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007760 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007761 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007762 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007763 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007764 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007765
7766 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007767 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7768 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007769 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007770 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7771 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007772 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007773 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7774 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007775 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007776 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7777 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007778 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007779 typeId = builder.makeBoolType();
7780 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007781 break;
7782 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007783 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007784 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007785 break;
7786 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007787 typeId = builder.makeFloatType(32);
7788 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007789 break;
7790 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007791 typeId = builder.makeIntType(32);
7792 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007793 break;
7794 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007795 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007796 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007797 break;
7798 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007799 typeId = builder.makeIntType(32);
7800 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007801 break;
7802 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007803 typeId = builder.makeIntType(32);
7804 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007805 break;
7806 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007807 typeId = builder.makeIntType(32);
7808 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007809 break;
7810 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007811 typeId = builder.makeIntType(32);
7812 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007813 break;
7814 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007815 typeId = builder.makeIntType(32);
7816 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007817 break;
7818 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007819 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7820 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007821 break;
7822 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007823 typeId = builder.makeBoolType();
7824 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007825 break;
7826 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007827 typeId = builder.makeBoolType();
7828 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007829 break;
7830 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007831 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7832 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007833 break;
7834 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007835 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7836 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007837 break;
7838 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007839 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7840 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007841 break;
7842 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007843 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7844 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007845 break;
7846 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007847 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007848 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007849 break;
7850 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007851 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007852 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007853 break;
Chao Chen3c366992018-09-19 11:41:59 -07007854 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7855 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7856 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007857 case glslang::EOpCooperativeMatrixMulAdd:
7858 opCode = spv::OpCooperativeMatrixMulAddNV;
7859 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007860#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007861 default:
7862 return 0;
7863 }
7864
7865 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007866 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007867 // Use an extended instruction from the standard library.
7868 // Construct the call arguments, without modifying the original operands vector.
7869 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7870 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007871 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007872 } else if (opCode == spv::OpDot && !isFloat) {
7873 // int dot(int, int)
7874 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7875 const int componentCount = builder.getNumComponents(operands[0]);
7876 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7877 builder.setPrecision(mulOp, precision);
7878 id = builder.createCompositeExtract(mulOp, typeId, 0);
7879 for (int i = 1; i < componentCount; ++i) {
7880 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007881 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007882 }
John Kessenich2359bd02015-12-06 19:29:11 -07007883 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007884 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007885 case 0:
7886 // should all be handled by visitAggregate and createNoArgOperation
7887 assert(0);
7888 return 0;
7889 case 1:
7890 // should all be handled by createUnaryOperation
7891 assert(0);
7892 return 0;
7893 case 2:
7894 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7895 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007896 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007897 // anything 3 or over doesn't have l-value operands, so all should be consumed
7898 assert(consumedOperands == operands.size());
7899 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007900 break;
7901 }
7902 }
7903
John Kessenichb9197c82019-08-11 07:41:45 -06007904#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007905 // Decode the return types that were structures
7906 switch (op) {
7907 case glslang::EOpAddCarry:
7908 case glslang::EOpSubBorrow:
7909 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7910 id = builder.createCompositeExtract(id, typeId0, 0);
7911 break;
7912 case glslang::EOpUMulExtended:
7913 case glslang::EOpIMulExtended:
7914 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7915 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7916 break;
7917 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007918 {
7919 assert(operands.size() == 2);
7920 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7921 // "exp" is floating-point type (from HLSL intrinsic)
7922 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7923 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7924 builder.createStore(member1, operands[1]);
7925 } else
7926 // "exp" is integer type (from GLSL built-in function)
7927 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7928 id = builder.createCompositeExtract(id, typeId0, 0);
7929 }
John Kessenich55e7d112015-11-15 21:33:39 -07007930 break;
7931 default:
7932 break;
7933 }
John Kessenichb9197c82019-08-11 07:41:45 -06007934#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007935
John Kessenich32cfd492016-02-02 12:37:46 -07007936 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007937}
7938
Rex Xu9d93a232016-05-05 12:30:44 +08007939// Intrinsics with no arguments (or no return value, and no precision).
7940spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007941{
Jeff Bolz36831c92018-09-05 10:11:41 -05007942 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007943 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7944 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007945
7946 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007947 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007948 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007949 if (glslangIntermediate->usingVulkanMemoryModel()) {
7950 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7951 spv::MemorySemanticsOutputMemoryKHRMask |
7952 spv::MemorySemanticsAcquireReleaseMask);
7953 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7954 } else {
7955 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7956 }
John Kessenich82979362017-12-11 04:02:24 -07007957 } else {
7958 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7959 spv::MemorySemanticsWorkgroupMemoryMask |
7960 spv::MemorySemanticsAcquireReleaseMask);
7961 }
John Kessenich140f3df2015-06-26 16:58:36 -06007962 return 0;
7963 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007964 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7965 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007966 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007967 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007968 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7969 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007970 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007971 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007972 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7973 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007974 return 0;
7975 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007976 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7977 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007978 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007979#ifndef GLSLANG_WEB
7980 case glslang::EOpMemoryBarrierAtomicCounter:
7981 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7982 spv::MemorySemanticsAcquireReleaseMask);
7983 return 0;
7984 case glslang::EOpMemoryBarrierImage:
7985 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7986 spv::MemorySemanticsAcquireReleaseMask);
7987 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007988 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007989 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007990 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007991 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007992 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007993 case glslang::EOpDeviceMemoryBarrier:
7994 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7995 spv::MemorySemanticsImageMemoryMask |
7996 spv::MemorySemanticsAcquireReleaseMask);
7997 return 0;
7998 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7999 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8000 spv::MemorySemanticsImageMemoryMask |
8001 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008002 return 0;
8003 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008004 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8005 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008006 return 0;
8007 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008008 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8009 spv::MemorySemanticsWorkgroupMemoryMask |
8010 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008011 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008012 case glslang::EOpSubgroupBarrier:
8013 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8014 spv::MemorySemanticsAcquireReleaseMask);
8015 return spv::NoResult;
8016 case glslang::EOpSubgroupMemoryBarrier:
8017 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8018 spv::MemorySemanticsAcquireReleaseMask);
8019 return spv::NoResult;
8020 case glslang::EOpSubgroupMemoryBarrierBuffer:
8021 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8022 spv::MemorySemanticsAcquireReleaseMask);
8023 return spv::NoResult;
8024 case glslang::EOpSubgroupMemoryBarrierImage:
8025 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8026 spv::MemorySemanticsAcquireReleaseMask);
8027 return spv::NoResult;
8028 case glslang::EOpSubgroupMemoryBarrierShared:
8029 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8030 spv::MemorySemanticsAcquireReleaseMask);
8031 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008032
8033 case glslang::EOpEmitVertex:
8034 builder.createNoResultOp(spv::OpEmitVertex);
8035 return 0;
8036 case glslang::EOpEndPrimitive:
8037 builder.createNoResultOp(spv::OpEndPrimitive);
8038 return 0;
8039
John Kessenich66011cb2018-03-06 16:12:04 -07008040 case glslang::EOpSubgroupElect: {
8041 std::vector<spv::Id> operands;
8042 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8043 }
Rex Xu9d93a232016-05-05 12:30:44 +08008044 case glslang::EOpTime:
8045 {
8046 std::vector<spv::Id> args; // Dummy arguments
8047 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8048 return builder.setPrecision(id, precision);
8049 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008050 case glslang::EOpIgnoreIntersection:
8051 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008052 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008053 case glslang::EOpTerminateRay:
8054 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008055 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008056 case glslang::EOpRayQueryInitialize:
8057 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8058 return 0;
8059 case glslang::EOpRayQueryTerminate:
8060 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8061 return 0;
8062 case glslang::EOpRayQueryGenerateIntersection:
8063 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8064 return 0;
8065 case glslang::EOpRayQueryConfirmIntersection:
8066 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8067 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008068 case glslang::EOpBeginInvocationInterlock:
8069 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8070 return 0;
8071 case glslang::EOpEndInvocationInterlock:
8072 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8073 return 0;
8074
Jeff Bolzba6170b2019-07-01 09:23:23 -05008075 case glslang::EOpIsHelperInvocation:
8076 {
8077 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008078 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8079 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8080 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008081 }
8082
amhagan91fb0092019-07-10 21:14:38 -04008083 case glslang::EOpReadClockSubgroupKHR: {
8084 std::vector<spv::Id> args;
8085 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8086 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8087 builder.addCapability(spv::CapabilityShaderClockKHR);
8088 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8089 }
8090
8091 case glslang::EOpReadClockDeviceKHR: {
8092 std::vector<spv::Id> args;
8093 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8094 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8095 builder.addCapability(spv::CapabilityShaderClockKHR);
8096 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8097 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008098#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008099 default:
John Kessenich155d3512019-08-08 23:29:20 -06008100 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008101 }
John Kessenich155d3512019-08-08 23:29:20 -06008102
8103 logger->missingFunctionality("unknown operation with no arguments");
8104
8105 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008106}
8107
8108spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8109{
John Kessenich2f273362015-07-18 22:34:27 -06008110 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008111 spv::Id id;
8112 if (symbolValues.end() != iter) {
8113 id = iter->second;
8114 return id;
8115 }
8116
8117 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008118 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008119 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008120 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008121 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008122 if (forcedType.second != spv::NoType)
8123 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008124
Rex Xuc884b4a2016-06-29 15:03:44 +08008125 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008126 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8127 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8128 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008129#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008130 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008131 if (symbol->getQualifier().hasComponent())
8132 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8133 if (symbol->getQualifier().hasIndex())
8134 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008135#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008136 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008137 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008138 // atomic counters use this:
8139 if (symbol->getQualifier().hasOffset())
8140 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008141 }
8142
scygan2c864272016-05-18 18:09:17 +02008143 if (symbol->getQualifier().hasLocation())
8144 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008145 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008146 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008147 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008148 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008149 }
John Kessenich140f3df2015-06-26 16:58:36 -06008150 if (symbol->getQualifier().hasSet())
8151 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008152 else if (IsDescriptorResource(symbol->getType())) {
8153 // default to 0
8154 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8155 }
John Kessenich140f3df2015-06-26 16:58:36 -06008156 if (symbol->getQualifier().hasBinding())
8157 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008158 else if (IsDescriptorResource(symbol->getType())) {
8159 // default to 0
8160 builder.addDecoration(id, spv::DecorationBinding, 0);
8161 }
John Kessenich6c292d32016-02-15 20:58:50 -07008162 if (symbol->getQualifier().hasAttachment())
8163 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008164 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008165 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008166 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008167 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008168 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8169 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8170 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8171 }
8172 if (symbol->getQualifier().hasXfbOffset())
8173 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008174 }
8175
John Kessenichb9197c82019-08-11 07:41:45 -06008176 // add built-in variable decoration
8177 if (builtIn != spv::BuiltInMax) {
8178 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8179 }
8180
8181#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008182 if (symbol->getType().isImage()) {
8183 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008184 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8185 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008186 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008187 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008188 }
8189
John Kessenich5611c6d2018-04-05 11:25:02 -06008190 // nonuniform
8191 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8192
chaoc0ad6a4e2016-12-19 16:29:34 -08008193 if (builtIn == spv::BuiltInSampleMask) {
8194 spv::Decoration decoration;
8195 // GL_NV_sample_mask_override_coverage extension
8196 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008197 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008198 else
8199 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008200 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008201 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008202 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008203 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8204 }
8205 }
chaoc771d89f2017-01-13 01:10:53 -08008206 else if (builtIn == spv::BuiltInLayer) {
8207 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008208 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008209 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008210 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8211 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8212 }
John Kessenichb41bff62017-08-11 13:07:17 -06008213 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008214 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8215 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008216 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8217 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8218 }
8219 }
8220
chaoc6e5acae2016-12-20 13:28:52 -08008221 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008222 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008223 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008224 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8225 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008226 if (symbol->getQualifier().pervertexNV) {
8227 builder.addDecoration(id, spv::DecorationPerVertexNV);
8228 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8229 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8230 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008231
John Kessenich5d610ee2018-03-07 18:05:55 -07008232 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8233 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8234 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8235 symbol->getType().getQualifier().semanticName);
8236 }
8237
John Kessenich7015bd62019-08-01 03:28:08 -06008238 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008239 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8240 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008241 }
John Kessenichb9197c82019-08-11 07:41:45 -06008242#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008243
John Kessenich140f3df2015-06-26 16:58:36 -06008244 return id;
8245}
8246
John Kessenicha28f7a72019-08-06 07:00:58 -06008247#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008248// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8249void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8250{
8251 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008252 if (qualifier.perPrimitiveNV) {
8253 // Need to add capability/extension for fragment shader.
8254 // Mesh shader already adds this by default.
8255 if (glslangIntermediate->getStage() == EShLangFragment) {
8256 builder.addCapability(spv::CapabilityMeshShadingNV);
8257 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8258 }
Chao Chen3c366992018-09-19 11:41:59 -07008259 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008260 }
Chao Chen3c366992018-09-19 11:41:59 -07008261 if (qualifier.perViewNV)
8262 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8263 if (qualifier.perTaskNV)
8264 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8265 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008266 if (qualifier.perPrimitiveNV) {
8267 // Need to add capability/extension for fragment shader.
8268 // Mesh shader already adds this by default.
8269 if (glslangIntermediate->getStage() == EShLangFragment) {
8270 builder.addCapability(spv::CapabilityMeshShadingNV);
8271 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8272 }
Chao Chen3c366992018-09-19 11:41:59 -07008273 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008274 }
Chao Chen3c366992018-09-19 11:41:59 -07008275 if (qualifier.perViewNV)
8276 builder.addDecoration(id, spv::DecorationPerViewNV);
8277 if (qualifier.perTaskNV)
8278 builder.addDecoration(id, spv::DecorationPerTaskNV);
8279 }
8280}
8281#endif
8282
John Kessenich55e7d112015-11-15 21:33:39 -07008283// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008284// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008285//
8286// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8287//
8288// Recursively walk the nodes. The nodes form a tree whose leaves are
8289// regular constants, which themselves are trees that createSpvConstant()
8290// recursively walks. So, this function walks the "top" of the tree:
8291// - emit specialization constant-building instructions for specConstant
8292// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008293spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008294{
John Kessenich7cc0e282016-03-20 00:46:02 -06008295 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008296
qining4f4bb812016-04-03 23:55:17 -04008297 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008298 if (! node.getQualifier().specConstant) {
8299 // hand off to the non-spec-constant path
8300 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8301 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008302 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8303 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8304 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008305 }
8306
8307 // We now know we have a specialization constant to build
8308
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008309 // Extra capabilities may be needed.
8310 if (node.getType().contains8BitInt())
8311 builder.addCapability(spv::CapabilityInt8);
8312 if (node.getType().contains16BitFloat())
8313 builder.addCapability(spv::CapabilityFloat16);
8314 if (node.getType().contains16BitInt())
8315 builder.addCapability(spv::CapabilityInt16);
8316 if (node.getType().contains64BitInt())
8317 builder.addCapability(spv::CapabilityInt64);
8318 if (node.getType().containsDouble())
8319 builder.addCapability(spv::CapabilityFloat64);
8320
John Kessenichd94c0032016-05-30 19:29:40 -06008321 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008322 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8323 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8324 std::vector<spv::Id> dimConstId;
8325 for (int dim = 0; dim < 3; ++dim) {
8326 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8327 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008328 if (specConst) {
8329 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8330 glslangIntermediate->getLocalSizeSpecId(dim));
8331 }
qining4f4bb812016-04-03 23:55:17 -04008332 }
8333 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8334 }
8335
8336 // An AST node labelled as specialization constant should be a symbol node.
8337 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8338 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008339 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008340 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008341 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8342 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8343 // will set the builder into spec constant op instruction generating mode.
8344 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008345 result = accessChainLoad(sub_tree->getType());
8346 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008347 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008348 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008349 } else {
8350 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008351 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008352 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008353 builder.addName(result, sn->getName().c_str());
8354 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008355 }
qining4f4bb812016-04-03 23:55:17 -04008356
8357 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8358 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008359 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008360 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008361}
8362
John Kessenich140f3df2015-06-26 16:58:36 -06008363// Use 'consts' as the flattened glslang source of scalar constants to recursively
8364// build the aggregate SPIR-V constant.
8365//
8366// If there are not enough elements present in 'consts', 0 will be substituted;
8367// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8368//
John Kessenich8985fc92020-03-03 10:25:07 -07008369spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8370 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008371{
8372 // vector of constants for SPIR-V
8373 std::vector<spv::Id> spvConsts;
8374
8375 // Type is used for struct and array constants
8376 spv::Id typeId = convertGlslangToSpvType(glslangType);
8377
8378 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008379 glslang::TType elementType(glslangType, 0);
8380 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008381 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008382 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008383 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008384 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008385 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008386 } else if (glslangType.isCoopMat()) {
8387 glslang::TType componentType(glslangType.getBasicType());
8388 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008389 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008390 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8391 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008392 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008393 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008394 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8395 bool zero = nextConst >= consts.size();
8396 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008397 case glslang::EbtInt:
8398 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8399 break;
8400 case glslang::EbtUint:
8401 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8402 break;
8403 case glslang::EbtFloat:
8404 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8405 break;
8406 case glslang::EbtBool:
8407 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8408 break;
8409#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008410 case glslang::EbtInt8:
8411 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8412 break;
8413 case glslang::EbtUint8:
8414 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8415 break;
8416 case glslang::EbtInt16:
8417 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8418 break;
8419 case glslang::EbtUint16:
8420 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8421 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008422 case glslang::EbtInt64:
8423 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8424 break;
8425 case glslang::EbtUint64:
8426 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8427 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008428 case glslang::EbtDouble:
8429 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8430 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008431 case glslang::EbtFloat16:
8432 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8433 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008434#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008435 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008436 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008437 break;
8438 }
8439 ++nextConst;
8440 }
8441 } else {
8442 // we have a non-aggregate (scalar) constant
8443 bool zero = nextConst >= consts.size();
8444 spv::Id scalar = 0;
8445 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008446 case glslang::EbtInt:
8447 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8448 break;
8449 case glslang::EbtUint:
8450 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8451 break;
8452 case glslang::EbtFloat:
8453 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8454 break;
8455 case glslang::EbtBool:
8456 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8457 break;
8458#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008459 case glslang::EbtInt8:
8460 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8461 break;
8462 case glslang::EbtUint8:
8463 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8464 break;
8465 case glslang::EbtInt16:
8466 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8467 break;
8468 case glslang::EbtUint16:
8469 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8470 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008471 case glslang::EbtInt64:
8472 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8473 break;
8474 case glslang::EbtUint64:
8475 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8476 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008477 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008478 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008479 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008480 case glslang::EbtFloat16:
8481 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8482 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008483 case glslang::EbtReference:
8484 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8485 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8486 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008487#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008488 case glslang::EbtString:
8489 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8490 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008491 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008492 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008493 break;
8494 }
8495 ++nextConst;
8496 return scalar;
8497 }
8498
8499 return builder.makeCompositeConstant(typeId, spvConsts);
8500}
8501
John Kessenich7c1aa102015-10-15 13:29:11 -06008502// Return true if the node is a constant or symbol whose reading has no
8503// non-trivial observable cost or effect.
8504bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8505{
8506 // don't know what this is
8507 if (node == nullptr)
8508 return false;
8509
8510 // a constant is safe
8511 if (node->getAsConstantUnion() != nullptr)
8512 return true;
8513
8514 // not a symbol means non-trivial
8515 if (node->getAsSymbolNode() == nullptr)
8516 return false;
8517
8518 // a symbol, depends on what's being read
8519 switch (node->getType().getQualifier().storage) {
8520 case glslang::EvqTemporary:
8521 case glslang::EvqGlobal:
8522 case glslang::EvqIn:
8523 case glslang::EvqInOut:
8524 case glslang::EvqConst:
8525 case glslang::EvqConstReadOnly:
8526 case glslang::EvqUniform:
8527 return true;
8528 default:
8529 return false;
8530 }
qining25262b32016-05-06 17:25:16 -04008531}
John Kessenich7c1aa102015-10-15 13:29:11 -06008532
8533// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008534// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008535// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008536// Return true if trivial.
8537bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8538{
8539 if (node == nullptr)
8540 return false;
8541
John Kessenich84cc15f2017-05-24 16:44:47 -06008542 // count non scalars as trivial, as well as anything coming from HLSL
8543 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008544 return true;
8545
John Kessenich7c1aa102015-10-15 13:29:11 -06008546 // symbols and constants are trivial
8547 if (isTrivialLeaf(node))
8548 return true;
8549
8550 // otherwise, it needs to be a simple operation or one or two leaf nodes
8551
8552 // not a simple operation
8553 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8554 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8555 if (binaryNode == nullptr && unaryNode == nullptr)
8556 return false;
8557
8558 // not on leaf nodes
8559 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8560 return false;
8561
8562 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8563 return false;
8564 }
8565
8566 switch (node->getAsOperator()->getOp()) {
8567 case glslang::EOpLogicalNot:
8568 case glslang::EOpConvIntToBool:
8569 case glslang::EOpConvUintToBool:
8570 case glslang::EOpConvFloatToBool:
8571 case glslang::EOpConvDoubleToBool:
8572 case glslang::EOpEqual:
8573 case glslang::EOpNotEqual:
8574 case glslang::EOpLessThan:
8575 case glslang::EOpGreaterThan:
8576 case glslang::EOpLessThanEqual:
8577 case glslang::EOpGreaterThanEqual:
8578 case glslang::EOpIndexDirect:
8579 case glslang::EOpIndexDirectStruct:
8580 case glslang::EOpLogicalXor:
8581 case glslang::EOpAny:
8582 case glslang::EOpAll:
8583 return true;
8584 default:
8585 return false;
8586 }
8587}
8588
8589// Emit short-circuiting code, where 'right' is never evaluated unless
8590// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008591spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8592 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008593{
8594 spv::Id boolTypeId = builder.makeBoolType();
8595
8596 // emit left operand
8597 builder.clearAccessChain();
8598 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008599 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008600
8601 // Operands to accumulate OpPhi operands
8602 std::vector<spv::Id> phiOperands;
8603 // accumulate left operand's phi information
8604 phiOperands.push_back(leftId);
8605 phiOperands.push_back(builder.getBuildPoint()->getId());
8606
8607 // Make the two kinds of operation symmetric with a "!"
8608 // || => emit "if (! left) result = right"
8609 // && => emit "if ( left) result = right"
8610 //
8611 // TODO: this runtime "not" for || could be avoided by adding functionality
8612 // to 'builder' to have an "else" without an "then"
8613 if (op == glslang::EOpLogicalOr)
8614 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8615
8616 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008617 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008618
8619 // emit right operand as the "then" part of the "if"
8620 builder.clearAccessChain();
8621 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008622 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008623
8624 // accumulate left operand's phi information
8625 phiOperands.push_back(rightId);
8626 phiOperands.push_back(builder.getBuildPoint()->getId());
8627
8628 // finish the "if"
8629 ifBuilder.makeEndIf();
8630
8631 // phi together the two results
8632 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8633}
8634
John Kessenicha28f7a72019-08-06 07:00:58 -06008635#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008636// Return type Id of the imported set of extended instructions corresponds to the name.
8637// Import this set if it has not been imported yet.
8638spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8639{
8640 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8641 return extBuiltinMap[name];
8642 else {
Rex Xu51596642016-09-21 18:56:12 +08008643 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008644 spv::Id extBuiltins = builder.import(name);
8645 extBuiltinMap[name] = extBuiltins;
8646 return extBuiltins;
8647 }
8648}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008649#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008650
John Kessenich140f3df2015-06-26 16:58:36 -06008651}; // end anonymous namespace
8652
8653namespace glslang {
8654
John Kessenich68d78fd2015-07-12 19:28:10 -06008655void GetSpirvVersion(std::string& version)
8656{
John Kessenich9e55f632015-07-15 10:03:39 -06008657 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008658 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008659 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008660 version = buf;
8661}
8662
John Kessenicha372a3e2017-11-02 22:32:14 -06008663// For low-order part of the generator's magic number. Bump up
8664// when there is a change in the style (e.g., if SSA form changes,
8665// or a different instruction sequence to do something gets used).
8666int GetSpirvGeneratorVersion()
8667{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008668 // return 1; // start
8669 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008670 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008671 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008672 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008673 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8674 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008675 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008676 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008677 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8678 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008679}
8680
John Kessenich140f3df2015-06-26 16:58:36 -06008681// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008682void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008683{
8684 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008685 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008686 if (out.fail())
8687 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008688 for (int i = 0; i < (int)spirv.size(); ++i) {
8689 unsigned int word = spirv[i];
8690 out.write((const char*)&word, 4);
8691 }
8692 out.close();
8693}
8694
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008695// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008696void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008697{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008698#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008699 std::ofstream out;
8700 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008701 if (out.fail())
8702 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008703 out << "\t// " <<
8704 GetSpirvGeneratorVersion() <<
8705 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8706 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008707 if (varName != nullptr) {
8708 out << "\t #pragma once" << std::endl;
8709 out << "const uint32_t " << varName << "[] = {" << std::endl;
8710 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008711 const int WORDS_PER_LINE = 8;
8712 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8713 out << "\t";
8714 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8715 const unsigned int word = spirv[i + j];
8716 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8717 if (i + j + 1 < (int)spirv.size()) {
8718 out << ",";
8719 }
8720 }
8721 out << std::endl;
8722 }
Flavio15017db2017-02-15 14:29:33 -08008723 if (varName != nullptr) {
8724 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008725 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008726 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008727 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008728#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008729}
8730
John Kessenich140f3df2015-06-26 16:58:36 -06008731//
8732// Set up the glslang traversal
8733//
John Kessenich4e11b612018-08-30 16:56:59 -06008734void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008735{
Lei Zhang17535f72016-05-04 15:55:59 -04008736 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008737 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008738}
8739
John Kessenich4e11b612018-08-30 16:56:59 -06008740void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008741 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008742{
John Kessenich140f3df2015-06-26 16:58:36 -06008743 TIntermNode* root = intermediate.getTreeRoot();
8744
8745 if (root == 0)
8746 return;
8747
John Kessenich4e11b612018-08-30 16:56:59 -06008748 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008749 if (options == nullptr)
8750 options = &defaultOptions;
8751
John Kessenich4e11b612018-08-30 16:56:59 -06008752 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008753
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008754 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008755 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008756 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008757 it.dumpSpv(spirv);
8758
GregFfb03a552018-03-29 11:49:14 -06008759#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008760 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8761 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008762 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008763 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8764 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008765 prelegalization = false;
8766 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008767 else if (options->stripDebugInfo) {
8768 // Strip debug info even if optimization is disabled.
8769 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8770 }
John Kessenich717c80a2018-08-23 15:17:10 -06008771
John Kessenich4e11b612018-08-30 16:56:59 -06008772 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008773 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008774
John Kessenich717c80a2018-08-23 15:17:10 -06008775 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008776 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008777
GregFcd1f1692017-09-21 18:40:22 -06008778#endif
8779
John Kessenich4e11b612018-08-30 16:56:59 -06008780 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008781}
8782
8783}; // end namespace glslang