blob: d32c6464be69c6b7108c99d63a28ba9a5b6537c3 [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
Chowa315b562020-07-02 15:50:36 +0800772 case glslang::EbvShadingRateKHR:
773 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
774 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
775 return spv::BuiltInShadingRateKHR;
776
777 case glslang::EbvPrimitiveShadingRateKHR:
778 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
779 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
780 return spv::BuiltInPrimitiveShadingRateKHR;
781
John Kessenich140f3df2015-06-26 16:58:36 -0600782 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600783 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
784 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
785 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
786 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600787 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800788
Rex Xu574ab042016-04-14 16:53:07 +0800789 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800790 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800791 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
792 return spv::BuiltInSubgroupSize;
793
Rex Xu574ab042016-04-14 16:53:07 +0800794 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800795 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800796 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
797 return spv::BuiltInSubgroupLocalInvocationId;
798
Rex Xu574ab042016-04-14 16:53:07 +0800799 case glslang::EbvSubGroupEqMask:
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::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800803
Rex Xu574ab042016-04-14 16:53:07 +0800804 case glslang::EbvSubGroupGeMask:
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::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800808
Rex Xu574ab042016-04-14 16:53:07 +0800809 case glslang::EbvSubGroupGtMask:
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::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800813
Rex Xu574ab042016-04-14 16:53:07 +0800814 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800815 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
816 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600817 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800818
Rex Xu574ab042016-04-14 16:53:07 +0800819 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800820 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
821 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600822 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800823
John Kessenich66011cb2018-03-06 16:12:04 -0700824 case glslang::EbvNumSubgroups:
825 builder.addCapability(spv::CapabilityGroupNonUniform);
826 return spv::BuiltInNumSubgroups;
827
828 case glslang::EbvSubgroupID:
829 builder.addCapability(spv::CapabilityGroupNonUniform);
830 return spv::BuiltInSubgroupId;
831
832 case glslang::EbvSubgroupSize2:
833 builder.addCapability(spv::CapabilityGroupNonUniform);
834 return spv::BuiltInSubgroupSize;
835
836 case glslang::EbvSubgroupInvocation2:
837 builder.addCapability(spv::CapabilityGroupNonUniform);
838 return spv::BuiltInSubgroupLocalInvocationId;
839
840 case glslang::EbvSubgroupEqMask2:
841 builder.addCapability(spv::CapabilityGroupNonUniform);
842 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
843 return spv::BuiltInSubgroupEqMask;
844
845 case glslang::EbvSubgroupGeMask2:
846 builder.addCapability(spv::CapabilityGroupNonUniform);
847 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
848 return spv::BuiltInSubgroupGeMask;
849
850 case glslang::EbvSubgroupGtMask2:
851 builder.addCapability(spv::CapabilityGroupNonUniform);
852 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
853 return spv::BuiltInSubgroupGtMask;
854
855 case glslang::EbvSubgroupLeMask2:
856 builder.addCapability(spv::CapabilityGroupNonUniform);
857 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
858 return spv::BuiltInSubgroupLeMask;
859
860 case glslang::EbvSubgroupLtMask2:
861 builder.addCapability(spv::CapabilityGroupNonUniform);
862 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
863 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600864
Rex Xu17ff3432016-10-14 17:41:45 +0800865 case glslang::EbvBaryCoordNoPersp:
866 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
867 return spv::BuiltInBaryCoordNoPerspAMD;
868
869 case glslang::EbvBaryCoordNoPerspCentroid:
870 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
871 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
872
873 case glslang::EbvBaryCoordNoPerspSample:
874 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
875 return spv::BuiltInBaryCoordNoPerspSampleAMD;
876
877 case glslang::EbvBaryCoordSmooth:
878 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
879 return spv::BuiltInBaryCoordSmoothAMD;
880
881 case glslang::EbvBaryCoordSmoothCentroid:
882 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
883 return spv::BuiltInBaryCoordSmoothCentroidAMD;
884
885 case glslang::EbvBaryCoordSmoothSample:
886 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
887 return spv::BuiltInBaryCoordSmoothSampleAMD;
888
889 case glslang::EbvBaryCoordPullModel:
890 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
891 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800892
John Kessenich6c8aaac2017-02-27 01:20:51 -0700893 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600894 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700895 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700896 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700897
898 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600899 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700900 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700901 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700902
Daniel Koch5154db52018-11-26 10:01:58 -0500903 case glslang::EbvFragSizeEXT:
904 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
905 builder.addCapability(spv::CapabilityFragmentDensityEXT);
906 return spv::BuiltInFragSizeEXT;
907
908 case glslang::EbvFragInvocationCountEXT:
909 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
910 builder.addCapability(spv::CapabilityFragmentDensityEXT);
911 return spv::BuiltInFragInvocationCountEXT;
912
chaoc771d89f2017-01-13 01:10:53 -0800913 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800914 if (!memberDeclaration) {
915 builder.addExtension(spv::E_SPV_NV_viewport_array2);
916 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
917 }
chaoc771d89f2017-01-13 01:10:53 -0800918 return spv::BuiltInViewportMaskNV;
919 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800920 if (!memberDeclaration) {
921 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
922 builder.addCapability(spv::CapabilityShaderStereoViewNV);
923 }
chaoc771d89f2017-01-13 01:10:53 -0800924 return spv::BuiltInSecondaryPositionNV;
925 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800926 if (!memberDeclaration) {
927 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
928 builder.addCapability(spv::CapabilityShaderStereoViewNV);
929 }
chaoc771d89f2017-01-13 01:10:53 -0800930 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800931 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800932 if (!memberDeclaration) {
933 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
934 builder.addCapability(spv::CapabilityPerViewAttributesNV);
935 }
chaocdf3956c2017-02-14 14:52:34 -0800936 return spv::BuiltInPositionPerViewNV;
937 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800938 if (!memberDeclaration) {
939 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
940 builder.addCapability(spv::CapabilityPerViewAttributesNV);
941 }
chaocdf3956c2017-02-14 14:52:34 -0800942 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700943 case glslang::EbvFragFullyCoveredNV:
944 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
945 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
946 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700947 case glslang::EbvFragmentSizeNV:
948 builder.addExtension(spv::E_SPV_NV_shading_rate);
949 builder.addCapability(spv::CapabilityShadingRateNV);
950 return spv::BuiltInFragmentSizeNV;
951 case glslang::EbvInvocationsPerPixelNV:
952 builder.addExtension(spv::E_SPV_NV_shading_rate);
953 builder.addCapability(spv::CapabilityShadingRateNV);
954 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700955
Daniel Koch593a4e02019-05-27 16:46:31 -0400956 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400957 case glslang::EbvLaunchId:
958 return spv::BuiltInLaunchIdKHR;
959 case glslang::EbvLaunchSize:
960 return spv::BuiltInLaunchSizeKHR;
961 case glslang::EbvWorldRayOrigin:
962 return spv::BuiltInWorldRayOriginKHR;
963 case glslang::EbvWorldRayDirection:
964 return spv::BuiltInWorldRayDirectionKHR;
965 case glslang::EbvObjectRayOrigin:
966 return spv::BuiltInObjectRayOriginKHR;
967 case glslang::EbvObjectRayDirection:
968 return spv::BuiltInObjectRayDirectionKHR;
969 case glslang::EbvRayTmin:
970 return spv::BuiltInRayTminKHR;
971 case glslang::EbvRayTmax:
972 return spv::BuiltInRayTmaxKHR;
973 case glslang::EbvInstanceCustomIndex:
974 return spv::BuiltInInstanceCustomIndexKHR;
975 case glslang::EbvHitT:
976 return spv::BuiltInHitTKHR;
977 case glslang::EbvHitKind:
978 return spv::BuiltInHitKindKHR;
979 case glslang::EbvObjectToWorld:
980 case glslang::EbvObjectToWorld3x4:
981 return spv::BuiltInObjectToWorldKHR;
982 case glslang::EbvWorldToObject:
983 case glslang::EbvWorldToObject3x4:
984 return spv::BuiltInWorldToObjectKHR;
985 case glslang::EbvIncomingRayFlags:
986 return spv::BuiltInIncomingRayFlagsKHR;
987 case glslang::EbvGeometryIndex:
988 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400989
990 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700991 case glslang::EbvBaryCoordNV:
992 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
993 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
994 return spv::BuiltInBaryCoordNV;
995 case glslang::EbvBaryCoordNoPerspNV:
996 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
997 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
998 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999
1000 // mesh shaders
1001 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001003 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001004 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001005 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001006 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001007 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001008 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001009 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001010 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001011 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001012 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001013 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001014 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001015 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001016 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001017
1018 // sm builtins
1019 case glslang::EbvWarpsPerSM:
1020 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1021 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1022 return spv::BuiltInWarpsPerSMNV;
1023 case glslang::EbvSMCount:
1024 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1025 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1026 return spv::BuiltInSMCountNV;
1027 case glslang::EbvWarpID:
1028 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1029 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1030 return spv::BuiltInWarpIDNV;
1031 case glslang::EbvSMID:
1032 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1033 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1034 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001035#endif
1036
Rex Xu3e783f92017-02-22 16:44:48 +08001037 default:
1038 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001039 }
1040}
1041
Rex Xufc618912015-09-09 16:42:49 +08001042// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001043spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001044{
1045 assert(type.getBasicType() == glslang::EbtSampler);
1046
John Kessenichb9197c82019-08-11 07:41:45 -06001047#ifdef GLSLANG_WEB
1048 return spv::ImageFormatUnknown;
1049#endif
1050
John Kessenich5d0fa972016-02-15 11:57:00 -07001051 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001052 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001053 case glslang::ElfRg32f:
1054 case glslang::ElfRg16f:
1055 case glslang::ElfR11fG11fB10f:
1056 case glslang::ElfR16f:
1057 case glslang::ElfRgba16:
1058 case glslang::ElfRgb10A2:
1059 case glslang::ElfRg16:
1060 case glslang::ElfRg8:
1061 case glslang::ElfR16:
1062 case glslang::ElfR8:
1063 case glslang::ElfRgba16Snorm:
1064 case glslang::ElfRg16Snorm:
1065 case glslang::ElfRg8Snorm:
1066 case glslang::ElfR16Snorm:
1067 case glslang::ElfR8Snorm:
1068
1069 case glslang::ElfRg32i:
1070 case glslang::ElfRg16i:
1071 case glslang::ElfRg8i:
1072 case glslang::ElfR16i:
1073 case glslang::ElfR8i:
1074
1075 case glslang::ElfRgb10a2ui:
1076 case glslang::ElfRg32ui:
1077 case glslang::ElfRg16ui:
1078 case glslang::ElfRg8ui:
1079 case glslang::ElfR16ui:
1080 case glslang::ElfR8ui:
1081 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1082 break;
1083
1084 default:
1085 break;
1086 }
1087
1088 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001089 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001090 case glslang::ElfNone: return spv::ImageFormatUnknown;
1091 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1092 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1093 case glslang::ElfR32f: return spv::ImageFormatR32f;
1094 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1095 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1096 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1097 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1098 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1099 case glslang::ElfR16f: return spv::ImageFormatR16f;
1100 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1101 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1102 case glslang::ElfRg16: return spv::ImageFormatRg16;
1103 case glslang::ElfRg8: return spv::ImageFormatRg8;
1104 case glslang::ElfR16: return spv::ImageFormatR16;
1105 case glslang::ElfR8: return spv::ImageFormatR8;
1106 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1107 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1108 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1109 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1110 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1111 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1112 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1113 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1114 case glslang::ElfR32i: return spv::ImageFormatR32i;
1115 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1116 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1117 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1118 case glslang::ElfR16i: return spv::ImageFormatR16i;
1119 case glslang::ElfR8i: return spv::ImageFormatR8i;
1120 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1121 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1122 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1123 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1124 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1125 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1126 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1127 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1128 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1129 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001130 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001131 }
1132}
1133
John Kessenich8985fc92020-03-03 10:25:07 -07001134spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1135 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001136{
John Kesseniche18fd202018-01-30 11:01:39 -07001137 if (selectionNode.getFlatten())
1138 return spv::SelectionControlFlattenMask;
1139 if (selectionNode.getDontFlatten())
1140 return spv::SelectionControlDontFlattenMask;
1141 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001142}
1143
John Kessenich8985fc92020-03-03 10:25:07 -07001144spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1145 const
steve-lunargf1709e72017-05-02 20:14:50 -06001146{
John Kesseniche18fd202018-01-30 11:01:39 -07001147 if (switchNode.getFlatten())
1148 return spv::SelectionControlFlattenMask;
1149 if (switchNode.getDontFlatten())
1150 return spv::SelectionControlDontFlattenMask;
1151 return spv::SelectionControlMaskNone;
1152}
1153
John Kessenicha2858d92018-01-31 08:11:18 -07001154// return a non-0 dependency if the dependency argument must be set
1155spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001156 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001157{
1158 spv::LoopControlMask control = spv::LoopControlMaskNone;
1159
1160 if (loopNode.getDontUnroll())
1161 control = control | spv::LoopControlDontUnrollMask;
1162 if (loopNode.getUnroll())
1163 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001164 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001165 control = control | spv::LoopControlDependencyInfiniteMask;
1166 else if (loopNode.getLoopDependency() > 0) {
1167 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001168 operands.push_back((unsigned int)loopNode.getLoopDependency());
1169 }
1170 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1171 if (loopNode.getMinIterations() > 0) {
1172 control = control | spv::LoopControlMinIterationsMask;
1173 operands.push_back(loopNode.getMinIterations());
1174 }
1175 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1176 control = control | spv::LoopControlMaxIterationsMask;
1177 operands.push_back(loopNode.getMaxIterations());
1178 }
1179 if (loopNode.getIterationMultiple() > 1) {
1180 control = control | spv::LoopControlIterationMultipleMask;
1181 operands.push_back(loopNode.getIterationMultiple());
1182 }
1183 if (loopNode.getPeelCount() > 0) {
1184 control = control | spv::LoopControlPeelCountMask;
1185 operands.push_back(loopNode.getPeelCount());
1186 }
1187 if (loopNode.getPartialCount() > 0) {
1188 control = control | spv::LoopControlPartialCountMask;
1189 operands.push_back(loopNode.getPartialCount());
1190 }
John Kessenicha2858d92018-01-31 08:11:18 -07001191 }
John Kesseniche18fd202018-01-30 11:01:39 -07001192
1193 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001194}
1195
John Kessenicha5c5fb62017-05-05 05:09:58 -06001196// Translate glslang type to SPIR-V storage class.
1197spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1198{
Torosdagli06c2eee2020-03-19 11:09:57 -04001199 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001200 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001201 if (type.getQualifier().isPipeInput())
1202 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001203 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001204 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001205
1206 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001207 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001208 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001209 return spv::StorageClassAtomicCounter;
1210 if (type.containsOpaque())
1211 return spv::StorageClassUniformConstant;
1212 }
1213
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001214 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001215 type.getQualifier().isShaderRecord()) {
1216 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001217 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001218
John Kessenichbed4e4f2017-09-08 02:38:07 -06001219 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001220 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001221 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001222 }
1223
1224 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001225 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001226 return spv::StorageClassPushConstant;
1227 if (type.getBasicType() == glslang::EbtBlock)
1228 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001229 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001230 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001231
1232 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001233 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1234 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1235 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001236 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001237#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001238 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1239 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1240 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1241 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1242 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001243#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001244 default:
1245 assert(0);
1246 break;
1247 }
1248
1249 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001250}
1251
John Kessenich5611c6d2018-04-05 11:25:02 -06001252// Add capabilities pertaining to how an array is indexed.
1253void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1254 const glslang::TType& indexType)
1255{
John Kessenichb9197c82019-08-11 07:41:45 -06001256#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001257 if (indexType.getQualifier().isNonUniform()) {
1258 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001259 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001260 if (baseType.getBasicType() == glslang::EbtSampler) {
1261 if (baseType.getQualifier().hasAttachment())
1262 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001263 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001264 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001265 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001266 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1267 else if (baseType.isImage())
1268 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1269 else if (baseType.isTexture())
1270 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1271 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1272 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1273 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1274 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1275 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1276 }
1277 } else {
1278 // assume a dynamically uniform index
1279 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001280 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001281 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001282 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001283 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001284 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001285 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001286 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001287 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001288 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001289 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001290 }
1291 }
John Kessenichb9197c82019-08-11 07:41:45 -06001292#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001293}
1294
qining25262b32016-05-06 17:25:16 -04001295// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001296// descriptor set.
1297bool IsDescriptorResource(const glslang::TType& type)
1298{
John Kessenichf7497e22016-03-08 21:36:22 -07001299 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001300 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001301 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001302 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001303 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001304
1305 // non block...
1306 // basically samplerXXX/subpass/sampler/texture are all included
1307 // if they are the global-scope-class, not the function parameter
1308 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001309 if (type.getBasicType() == glslang::EbtSampler ||
1310 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001311 return type.getQualifier().isUniformOrBuffer();
1312
1313 // None of the above.
1314 return false;
1315}
1316
John Kesseniche0b6cad2015-12-24 10:30:13 -07001317void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1318{
1319 if (child.layoutMatrix == glslang::ElmNone)
1320 child.layoutMatrix = parent.layoutMatrix;
1321
1322 if (parent.invariant)
1323 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001324 if (parent.flat)
1325 child.flat = true;
1326 if (parent.centroid)
1327 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001328#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001329 if (parent.nopersp)
1330 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001331 if (parent.explicitInterp)
1332 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001333 if (parent.perPrimitiveNV)
1334 child.perPrimitiveNV = true;
1335 if (parent.perViewNV)
1336 child.perViewNV = true;
1337 if (parent.perTaskNV)
1338 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001339 if (parent.patch)
1340 child.patch = true;
1341 if (parent.sample)
1342 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001343 if (parent.coherent)
1344 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001345 if (parent.devicecoherent)
1346 child.devicecoherent = true;
1347 if (parent.queuefamilycoherent)
1348 child.queuefamilycoherent = true;
1349 if (parent.workgroupcoherent)
1350 child.workgroupcoherent = true;
1351 if (parent.subgroupcoherent)
1352 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001353 if (parent.shadercallcoherent)
1354 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001355 if (parent.nonprivate)
1356 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001357 if (parent.volatil)
1358 child.volatil = true;
1359 if (parent.restrict)
1360 child.restrict = true;
1361 if (parent.readonly)
1362 child.readonly = true;
1363 if (parent.writeonly)
1364 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001365#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001366}
1367
John Kessenichf2b7f332016-09-01 17:05:23 -06001368bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001369{
John Kessenich7b9fa252016-01-21 18:56:57 -07001370 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001371 // - struct members might inherit from a struct declaration
1372 // (note that non-block structs don't explicitly inherit,
1373 // only implicitly, meaning no decoration involved)
1374 // - affect decorations on the struct members
1375 // (note smooth does not, and expecting something like volatile
1376 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001377 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001378 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001379}
1380
John Kessenich140f3df2015-06-26 16:58:36 -06001381//
1382// Implement the TGlslangToSpvTraverser class.
1383//
1384
John Kessenich8985fc92020-03-03 10:25:07 -07001385TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1386 const glslang::TIntermediate* glslangIntermediate,
1387 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1388 TIntermTraverser(true, false, true),
1389 options(options),
1390 shaderEntry(nullptr), currentFunction(nullptr),
1391 sequenceDepth(0), logger(buildLogger),
1392 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1393 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1394 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001395 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1396 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001397{
1398 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1399
1400 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001401 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1402 glslangIntermediate->getVersion());
1403
John Kessenich121853f2017-05-31 17:11:16 -06001404 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001405 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001406 builder.setSourceFile(glslangIntermediate->getSourceFile());
1407
1408 // Set the source shader's text. If for SPV version 1.0, include
1409 // a preamble in comments stating the OpModuleProcessed instructions.
1410 // Otherwise, emit those as actual instructions.
1411 std::string text;
1412 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1413 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001414 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001415 text.append("// OpModuleProcessed ");
1416 text.append(processes[p]);
1417 text.append("\n");
1418 } else
1419 builder.addModuleProcessed(processes[p]);
1420 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001421 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001422 text.append("#line 1\n");
1423 text.append(glslangIntermediate->getSourceText());
1424 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001425 // Pass name and text for all included files
1426 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1427 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1428 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001429 }
John Kessenich140f3df2015-06-26 16:58:36 -06001430 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001431
1432 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1433 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1434
1435 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1436 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001437 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001438 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001439 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001440 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001441 memoryModel = spv::MemoryModelVulkanKHR;
1442 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001443 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001444 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001445 builder.setMemoryModel(addressingModel, memoryModel);
1446
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001447 if (glslangIntermediate->usingVariablePointers()) {
1448 builder.addCapability(spv::CapabilityVariablePointers);
1449 }
1450
John Kessenicheee9d532016-09-19 18:09:30 -06001451 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1452 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001453
1454 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001455 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1456 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001457 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001458
1459 // Add the top-level modes for this shader.
1460
John Kessenich92187592016-02-01 13:45:25 -07001461 if (glslangIntermediate->getXfbMode()) {
1462 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001463 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001464 }
John Kessenich140f3df2015-06-26 16:58:36 -06001465
alelenv59216d52020-05-21 04:38:41 -07001466 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001467 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1468 }
1469
John Kessenich140f3df2015-06-26 16:58:36 -06001470 unsigned int mode;
1471 switch (glslangIntermediate->getStage()) {
1472 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001473 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001474 break;
1475
John Kessenicha28f7a72019-08-06 07:00:58 -06001476 case EShLangFragment:
1477 builder.addCapability(spv::CapabilityShader);
1478 if (glslangIntermediate->getPixelCenterInteger())
1479 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1480
1481 if (glslangIntermediate->getOriginUpperLeft())
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1483 else
1484 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1485
1486 if (glslangIntermediate->getEarlyFragmentTests())
1487 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1488
1489 if (glslangIntermediate->getPostDepthCoverage()) {
1490 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1491 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1492 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1493 }
1494
John Kessenichb9197c82019-08-11 07:41:45 -06001495 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1496 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1497
1498#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001499
John Kessenicha28f7a72019-08-06 07:00:58 -06001500 switch(glslangIntermediate->getDepth()) {
1501 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1502 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1503 default: mode = spv::ExecutionModeMax; break;
1504 }
1505 if (mode != spv::ExecutionModeMax)
1506 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001507 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001508 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1509 break;
1510 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1511 break;
1512 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1513 break;
1514 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1515 break;
1516 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1517 break;
1518 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1519 break;
1520 default: mode = spv::ExecutionModeMax;
1521 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001522 }
1523 if (mode != spv::ExecutionModeMax) {
1524 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1525 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1526 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1527 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1528 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1529 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1530 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1531 } else {
1532 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1533 }
1534 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1535 }
John Kessenichb9197c82019-08-11 07:41:45 -06001536#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001537 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001538
John Kessenicha28f7a72019-08-06 07:00:58 -06001539 case EShLangCompute:
1540 builder.addCapability(spv::CapabilityShader);
1541 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1542 glslangIntermediate->getLocalSize(1),
1543 glslangIntermediate->getLocalSize(2));
1544 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1545 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1546 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1547 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1548 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1549 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1550 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1551 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1552 }
1553 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001554#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001555 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001556 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001557 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001558
steve-lunarge7412492017-03-23 11:56:07 -06001559 glslang::TLayoutGeometry primitive;
1560
1561 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001562 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1563 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001564 primitive = glslangIntermediate->getOutputPrimitive();
1565 } else {
1566 primitive = glslangIntermediate->getInputPrimitive();
1567 }
1568
1569 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001570 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1571 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1572 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001573 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001574 }
John Kessenich4016e382016-07-15 11:53:56 -06001575 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001576 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1577
John Kesseniche6903322015-10-13 16:29:02 -06001578 switch (glslangIntermediate->getVertexSpacing()) {
1579 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1580 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1581 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001582 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001583 }
John Kessenich4016e382016-07-15 11:53:56 -06001584 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001585 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1586
1587 switch (glslangIntermediate->getVertexOrder()) {
1588 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1589 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001590 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001591 }
John Kessenich4016e382016-07-15 11:53:56 -06001592 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001593 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1594
1595 if (glslangIntermediate->getPointMode())
1596 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001597 break;
1598
1599 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001600 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001601 switch (glslangIntermediate->getInputPrimitive()) {
1602 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1603 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1604 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001605 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001606 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001607 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001608 }
John Kessenich4016e382016-07-15 11:53:56 -06001609 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001610 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001611
John Kessenich140f3df2015-06-26 16:58:36 -06001612 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1613
1614 switch (glslangIntermediate->getOutputPrimitive()) {
1615 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1616 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1617 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001618 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001619 }
John Kessenich4016e382016-07-15 11:53:56 -06001620 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001621 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1622 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1623 break;
1624
Daniel Kochdb32b242020-03-17 20:42:47 -04001625 case EShLangRayGen:
1626 case EShLangIntersect:
1627 case EShLangAnyHit:
1628 case EShLangClosestHit:
1629 case EShLangMiss:
1630 case EShLangCallable:
1631 {
1632 auto& extensions = glslangIntermediate->getRequestedExtensions();
1633 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1634 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1635 builder.addExtension("SPV_KHR_ray_tracing");
1636 }
1637 else {
1638 builder.addCapability(spv::CapabilityRayTracingNV);
1639 builder.addExtension("SPV_NV_ray_tracing");
1640 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001641 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001642 }
Chao Chen3c366992018-09-19 11:41:59 -07001643 case EShLangTaskNV:
1644 case EShLangMeshNV:
1645 builder.addCapability(spv::CapabilityMeshShadingNV);
1646 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1647 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1648 glslangIntermediate->getLocalSize(1),
1649 glslangIntermediate->getLocalSize(2));
1650 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001651 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1652 glslangIntermediate->getVertices());
1653 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1654 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001655
1656 switch (glslangIntermediate->getOutputPrimitive()) {
1657 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1658 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1659 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1660 default: mode = spv::ExecutionModeMax; break;
1661 }
1662 if (mode != spv::ExecutionModeMax)
1663 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1664 }
1665 break;
1666#endif
1667
John Kessenich140f3df2015-06-26 16:58:36 -06001668 default:
1669 break;
1670 }
John Kessenich140f3df2015-06-26 16:58:36 -06001671}
1672
John Kessenichfca82622016-11-26 13:23:20 -07001673// Finish creating SPV, after the traversal is complete.
1674void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001675{
John Kessenichf04c51b2018-08-03 15:56:12 -06001676 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001677 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001678 builder.setBuildPoint(shaderEntry->getLastBlock());
1679 builder.leaveFunction();
1680 }
1681
John Kessenich7ba63412015-12-20 17:37:07 -07001682 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001683 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1684 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001685
David Neto8c3d5b42019-10-21 14:50:31 -04001686 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001687 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001688 // Note: WebGPU code generation must have the opportunity to aggressively
1689 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001690 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001691}
1692
John Kessenichfca82622016-11-26 13:23:20 -07001693// Write the SPV into 'out'.
1694void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001695{
John Kessenichfca82622016-11-26 13:23:20 -07001696 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001697}
1698
1699//
1700// Implement the traversal functions.
1701//
1702// Return true from interior nodes to have the external traversal
1703// continue on to children. Return false if children were
1704// already processed.
1705//
1706
1707//
qining25262b32016-05-06 17:25:16 -04001708// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001709// - uniform/input reads
1710// - output writes
1711// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1712// - something simple that degenerates into the last bullet
1713//
1714void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1715{
qining75d1d802016-04-06 14:42:01 -04001716 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001717 if (symbol->getType().isStruct())
1718 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1719
qining75d1d802016-04-06 14:42:01 -04001720 if (symbol->getType().getQualifier().isSpecConstant())
1721 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1722
John Kessenich140f3df2015-06-26 16:58:36 -06001723 // getSymbolId() will set up all the IO decorations on the first call.
1724 // Formal function parameters were mapped during makeFunctions().
1725 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001726
John Kessenich7ba63412015-12-20 17:37:07 -07001727 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001728 if (!symbol->getType().getQualifier().isParamInput() &&
1729 !symbol->getType().getQualifier().isParamOutput()) {
1730 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1731 // Consider adding to the OpEntryPoint interface list.
1732 // Only looking at structures if they have at least one member.
1733 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1734 spv::StorageClass sc = builder.getStorageClass(id);
1735 // Before SPIR-V 1.4, we only want to include Input and Output.
1736 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001737 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001738 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1739 iOSet.insert(id);
1740 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001741 }
John Kessenich5f77d862017-09-19 11:09:59 -06001742 }
John Kessenich9c14f772019-06-17 08:38:35 -06001743
Daniel Kochdb32b242020-03-17 20:42:47 -04001744 // If the SPIR-V type is required to be different than the AST type
1745 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001746 // translate now from the SPIR-V type to the AST type, for the consuming
1747 // operation.
1748 // Note this turns it from an l-value to an r-value.
1749 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1750 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1751 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001752 }
1753
1754 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001755 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001756 // Prepare to generate code for the access
1757
1758 // L-value chains will be computed left to right. We're on the symbol now,
1759 // which is the left-most part of the access chain, so now is "clear" time,
1760 // followed by setting the base.
1761 builder.clearAccessChain();
1762
1763 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001764 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001765 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001766 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001767 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001768 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001769 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001770 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001771 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1772 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001773 builder.setAccessChainRValue(id);
1774 else
1775 builder.setAccessChainLValue(id);
1776 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001777
John Kessenichb9197c82019-08-11 07:41:45 -06001778#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001779 // Process linkage-only nodes for any special additional interface work.
1780 if (linkageOnly) {
1781 if (glslangIntermediate->getHlslFunctionality1()) {
1782 // Map implicit counter buffers to their originating buffers, which should have been
1783 // seen by now, given earlier pruning of unused counters, and preservation of order
1784 // of declaration.
1785 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1786 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1787 // Save possible originating buffers for counter buffers, keyed by
1788 // making the potential counter-buffer name.
1789 std::string keyName = symbol->getName().c_str();
1790 keyName = glslangIntermediate->addCounterBufferName(keyName);
1791 counterOriginator[keyName] = symbol;
1792 } else {
1793 // Handle a counter buffer, by finding the saved originating buffer.
1794 std::string keyName = symbol->getName().c_str();
1795 auto it = counterOriginator.find(keyName);
1796 if (it != counterOriginator.end()) {
1797 id = getSymbolId(it->second);
1798 if (id != spv::NoResult) {
1799 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001800 if (counterId != spv::NoResult) {
1801 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001802 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001803 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001804 }
1805 }
1806 }
1807 }
1808 }
1809 }
John Kessenich155d3512019-08-08 23:29:20 -06001810#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001811}
1812
1813bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1814{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001815 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001816 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1817 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1818 }
1819 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1820 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1821 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001822
qining40887662016-04-03 22:20:42 -04001823 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1824 if (node->getType().getQualifier().isSpecConstant())
1825 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1826
John Kessenich140f3df2015-06-26 16:58:36 -06001827 // First, handle special cases
1828 switch (node->getOp()) {
1829 case glslang::EOpAssign:
1830 case glslang::EOpAddAssign:
1831 case glslang::EOpSubAssign:
1832 case glslang::EOpMulAssign:
1833 case glslang::EOpVectorTimesMatrixAssign:
1834 case glslang::EOpVectorTimesScalarAssign:
1835 case glslang::EOpMatrixTimesScalarAssign:
1836 case glslang::EOpMatrixTimesMatrixAssign:
1837 case glslang::EOpDivAssign:
1838 case glslang::EOpModAssign:
1839 case glslang::EOpAndAssign:
1840 case glslang::EOpInclusiveOrAssign:
1841 case glslang::EOpExclusiveOrAssign:
1842 case glslang::EOpLeftShiftAssign:
1843 case glslang::EOpRightShiftAssign:
1844 // A bin-op assign "a += b" means the same thing as "a = a + b"
1845 // where a is evaluated before b. For a simple assignment, GLSL
1846 // says to evaluate the left before the right. So, always, left
1847 // node then right node.
1848 {
1849 // get the left l-value, save it away
1850 builder.clearAccessChain();
1851 node->getLeft()->traverse(this);
1852 spv::Builder::AccessChain lValue = builder.getAccessChain();
1853
1854 // evaluate the right
1855 builder.clearAccessChain();
1856 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001857 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001858
1859 if (node->getOp() != glslang::EOpAssign) {
1860 // the left is also an r-value
1861 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001862 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001863
1864 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001865 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001866 TranslateNoContractionDecoration(node->getType().getQualifier()),
1867 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001868 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001869 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1870 node->getType().getBasicType());
1871
1872 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001873 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001874 }
1875
1876 // store the result
1877 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001878 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001879
1880 // assignments are expressions having an rValue after they are evaluated...
1881 builder.clearAccessChain();
1882 builder.setAccessChainRValue(rValue);
1883 }
1884 return false;
1885 case glslang::EOpIndexDirect:
1886 case glslang::EOpIndexDirectStruct:
1887 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001888 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001889 // Get the left part of the access chain.
1890 node->getLeft()->traverse(this);
1891
1892 // Add the next element in the chain
1893
David Netoa901ffe2016-06-08 14:11:40 +01001894 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001895 if (! node->getLeft()->getType().isArray() &&
1896 node->getLeft()->getType().isVector() &&
1897 node->getOp() == glslang::EOpIndexDirect) {
1898 // This is essentially a hard-coded vector swizzle of size 1,
1899 // so short circuit the access-chain stuff with a swizzle.
1900 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001901 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001902 int dummySize;
1903 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1904 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001905 glslangIntermediate->getBaseAlignmentScalar(
1906 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001907 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001908
1909 // Load through a block reference is performed with a dot operator that
1910 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1911 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001912 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001913 !node->getLeft()->getType().isArray() &&
1914 node->getOp() == glslang::EOpIndexDirectStruct)
1915 {
1916 spv::Id left = accessChainLoad(node->getLeft()->getType());
1917 builder.clearAccessChain();
1918 builder.setAccessChainLValue(left);
1919 }
1920
David Netoa901ffe2016-06-08 14:11:40 +01001921 int spvIndex = glslangIndex;
1922 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1923 node->getOp() == glslang::EOpIndexDirectStruct)
1924 {
1925 // This may be, e.g., an anonymous block-member selection, which generally need
1926 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001927 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1928 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1929 std::vector<int>& remapper = memberRemapper[glslangId];
1930 assert(remapper.size() > 0);
1931 spvIndex = remapper[glslangIndex];
1932 }
David Netoa901ffe2016-06-08 14:11:40 +01001933 }
John Kessenichebb50532016-05-16 19:22:05 -06001934
David Netoa901ffe2016-06-08 14:11:40 +01001935 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001936 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1937 TranslateCoherent(node->getLeft()->getType()),
1938 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001939
1940 // Add capabilities here for accessing PointSize and clip/cull distance.
1941 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001942 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001943 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001944 }
1945 }
1946 return false;
1947 case glslang::EOpIndexIndirect:
1948 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001949 // Array, matrix, or vector indirection with variable index.
1950 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001951 // matrices are arrays of vectors, so will also work for a matrix.
1952 // Will use the access chain's 'component' for variable index into a vector.
1953
1954 // This adapter is building access chains left to right.
1955 // Set up the access chain to the left.
1956 node->getLeft()->traverse(this);
1957
1958 // save it so that computing the right side doesn't trash it
1959 spv::Builder::AccessChain partial = builder.getAccessChain();
1960
1961 // compute the next index in the chain
1962 builder.clearAccessChain();
1963 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001964 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001965
John Kessenich5611c6d2018-04-05 11:25:02 -06001966 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1967
John Kessenich140f3df2015-06-26 16:58:36 -06001968 // restore the saved access chain
1969 builder.setAccessChain(partial);
1970
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001971 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1972 int dummySize;
1973 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1974 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001975 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1976 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001977 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001978 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1979 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001980 }
1981 return false;
1982 case glslang::EOpVectorSwizzle:
1983 {
1984 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001985 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001986 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001987 int dummySize;
1988 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1989 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001990 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1991 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001992 }
1993 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001994 case glslang::EOpMatrixSwizzle:
1995 logger->missingFunctionality("matrix swizzle");
1996 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001997 case glslang::EOpLogicalOr:
1998 case glslang::EOpLogicalAnd:
1999 {
2000
2001 // These may require short circuiting, but can sometimes be done as straight
2002 // binary operations. The right operand must be short circuited if it has
2003 // side effects, and should probably be if it is complex.
2004 if (isTrivial(node->getRight()->getAsTyped()))
2005 break; // handle below as a normal binary operation
2006 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07002007 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
2008 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06002009 builder.clearAccessChain();
2010 builder.setAccessChainRValue(result);
2011 }
2012 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002013 default:
2014 break;
2015 }
2016
2017 // Assume generic binary op...
2018
John Kessenich32cfd492016-02-02 12:37:46 -07002019 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002020 builder.clearAccessChain();
2021 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002022 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002023
John Kessenich32cfd492016-02-02 12:37:46 -07002024 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002025 builder.clearAccessChain();
2026 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002027 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002028
John Kessenich32cfd492016-02-02 12:37:46 -07002029 // get result
John Kessenichead86222018-03-28 18:01:20 -06002030 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002031 TranslateNoContractionDecoration(node->getType().getQualifier()),
2032 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002033 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002034 convertGlslangToSpvType(node->getType()), left, right,
2035 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002036
John Kessenich50e57562015-12-21 21:21:11 -07002037 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002038 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002039 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002040 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002041 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002042 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002043 return false;
2044 }
John Kessenich140f3df2015-06-26 16:58:36 -06002045}
2046
John Kessenich9c14f772019-06-17 08:38:35 -06002047// Figure out what, if any, type changes are needed when accessing a specific built-in.
2048// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2049// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002050std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002051 const glslang::TType& glslangType)
2052{
Daniel Kochdb32b242020-03-17 20:42:47 -04002053 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002054 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002055 case glslang::EbvSubGroupEqMask:
2056 case glslang::EbvSubGroupGeMask:
2057 case glslang::EbvSubGroupGtMask:
2058 case glslang::EbvSubGroupLeMask:
2059 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002060 // these require changing a 64-bit scaler -> a vector of 32-bit components
2061 if (glslangType.isVector())
2062 break;
2063 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2064 builder.makeUintType(64));
2065 return ret;
2066 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002067 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2068 // builtins. During visitBinary we insert a transpose
2069 case glslang::EbvWorldToObject3x4:
2070 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002071 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2072 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2073 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002074 return ret;
2075 }
John Kessenich9c14f772019-06-17 08:38:35 -06002076 default:
2077 break;
2078 }
2079
2080 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2081 return ret;
2082}
2083
2084// For an object previously identified (see getForcedType() and forceType)
2085// as needing type translations, do the translation needed for a load, turning
2086// an L-value into in R-value.
2087spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2088{
2089 const auto forceIt = forceType.find(object);
2090 if (forceIt == forceType.end())
2091 return object;
2092
2093 spv::Id desiredTypeId = forceIt->second;
2094 spv::Id objectTypeId = builder.getTypeId(object);
2095 assert(builder.isPointerType(objectTypeId));
2096 objectTypeId = builder.getContainedTypeId(objectTypeId);
2097 if (builder.isVectorType(objectTypeId) &&
2098 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2099 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2100 // handle 32-bit v.xy* -> 64-bit
2101 builder.clearAccessChain();
2102 builder.setAccessChainLValue(object);
2103 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2104 std::vector<spv::Id> components;
2105 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2106 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2107
2108 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2109 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2110 builder.createCompositeConstruct(vecType, components));
2111 } else {
2112 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2113 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002114 } else if (builder.isMatrixType(objectTypeId)) {
2115 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2116 // and we insert a transpose after loading the original non-transposed builtins
2117 builder.clearAccessChain();
2118 builder.setAccessChainLValue(object);
2119 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2120 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2121
2122 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002123 logger->missingFunctionality("forcing non 32-bit vector type");
2124 }
2125
2126 return object;
2127}
2128
John Kessenich140f3df2015-06-26 16:58:36 -06002129bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2130{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002131 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002132
qining40887662016-04-03 22:20:42 -04002133 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2134 if (node->getType().getQualifier().isSpecConstant())
2135 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2136
John Kessenichfc51d282015-08-19 13:34:18 -06002137 spv::Id result = spv::NoResult;
2138
2139 // try texturing first
2140 result = createImageTextureFunctionCall(node);
2141 if (result != spv::NoResult) {
2142 builder.clearAccessChain();
2143 builder.setAccessChainRValue(result);
2144
2145 return false; // done with this node
2146 }
2147
2148 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002149
2150 if (node->getOp() == glslang::EOpArrayLength) {
2151 // Quite special; won't want to evaluate the operand.
2152
John Kessenich5611c6d2018-04-05 11:25:02 -06002153 // Currently, the front-end does not allow .length() on an array until it is sized,
2154 // except for the last block membeor of an SSBO.
2155 // TODO: If this changes, link-time sized arrays might show up here, and need their
2156 // size extracted.
2157
John Kessenichc9a80832015-09-12 12:17:44 -06002158 // Normal .length() would have been constant folded by the front-end.
2159 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002160 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002161
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002162 spv::Id length;
2163 if (node->getOperand()->getType().isCoopMat()) {
2164 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2165
2166 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2167 assert(builder.isCooperativeMatrixType(typeId));
2168
2169 length = builder.createCooperativeMatrixLength(typeId);
2170 } else {
2171 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2172 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002173 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2174 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002175 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2176 }
John Kessenichc9a80832015-09-12 12:17:44 -06002177
John Kessenich8c869672018-11-28 07:01:37 -07002178 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2179 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2180 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002181 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2182 if (builder.isInSpecConstCodeGenMode()) {
2183 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2184 } else {
2185 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2186 }
2187 }
John Kessenich8c869672018-11-28 07:01:37 -07002188
John Kessenichc9a80832015-09-12 12:17:44 -06002189 builder.clearAccessChain();
2190 builder.setAccessChainRValue(length);
2191
2192 return false;
2193 }
2194
John Kessenichfc51d282015-08-19 13:34:18 -06002195 // Start by evaluating the operand
2196
John Kessenich8c8505c2016-07-26 12:50:38 -06002197 // Does it need a swizzle inversion? If so, evaluation is inverted;
2198 // operate first on the swizzle base, then apply the swizzle.
2199 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002200 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2201 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002202 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2203 invertedType = getInvertedSwizzleType(*node->getOperand());
2204
John Kessenich140f3df2015-06-26 16:58:36 -06002205 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002206 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002207 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002208 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002209 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002210 operandNode = node->getOperand();
2211
2212 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002213
Rex Xufc618912015-09-09 16:42:49 +08002214 spv::Id operand = spv::NoResult;
2215
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002216 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2217
John Kessenichfb4f2332019-08-09 03:49:15 -06002218#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002219 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2220 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002221 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002222 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2223 node->getOp() == glslang::EOpRayQueryProceed ||
2224 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2225 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2226 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2227 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2228 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2229 node->getOp() == glslang::EOpRayQueryTerminate ||
2230 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002231 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002232 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2233 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2234 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002235#endif
2236 {
John Kessenich32cfd492016-02-02 12:37:46 -07002237 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002238 }
John Kessenich140f3df2015-06-26 16:58:36 -06002239
John Kessenichead86222018-03-28 18:01:20 -06002240 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002241 TranslateNoContractionDecoration(node->getType().getQualifier()),
2242 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002243
2244 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002245 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002246 result = createConversion(node->getOp(), decorations, resultType(), operand,
2247 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002248
2249 // if not, then possibly an operation
2250 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002251 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2252 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002253
2254 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002255 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002256 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002257 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002258 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002259
John Kessenich140f3df2015-06-26 16:58:36 -06002260 builder.clearAccessChain();
2261 builder.setAccessChainRValue(result);
2262
2263 return false; // done with this node
2264 }
2265
2266 // it must be a special case, check...
2267 switch (node->getOp()) {
2268 case glslang::EOpPostIncrement:
2269 case glslang::EOpPostDecrement:
2270 case glslang::EOpPreIncrement:
2271 case glslang::EOpPreDecrement:
2272 {
2273 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002274 spv::Id one = 0;
2275 if (node->getBasicType() == glslang::EbtFloat)
2276 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002277#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002278 else if (node->getBasicType() == glslang::EbtDouble)
2279 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002280 else if (node->getBasicType() == glslang::EbtFloat16)
2281 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002282 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2283 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002284 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2285 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002286 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2287 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002288#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002289 else
2290 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002291 glslang::TOperator op;
2292 if (node->getOp() == glslang::EOpPreIncrement ||
2293 node->getOp() == glslang::EOpPostIncrement)
2294 op = glslang::EOpAdd;
2295 else
2296 op = glslang::EOpSub;
2297
John Kessenichead86222018-03-28 18:01:20 -06002298 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002299 convertGlslangToSpvType(node->getType()), operand, one,
2300 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002301 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002302
2303 // The result of operation is always stored, but conditionally the
2304 // consumed result. The consumed result is always an r-value.
2305 builder.accessChainStore(result);
2306 builder.clearAccessChain();
2307 if (node->getOp() == glslang::EOpPreIncrement ||
2308 node->getOp() == glslang::EOpPreDecrement)
2309 builder.setAccessChainRValue(result);
2310 else
2311 builder.setAccessChainRValue(operand);
2312 }
2313
2314 return false;
2315
John Kessenich155d3512019-08-08 23:29:20 -06002316#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002317 case glslang::EOpEmitStreamVertex:
2318 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2319 return false;
2320 case glslang::EOpEndStreamPrimitive:
2321 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2322 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002323 case glslang::EOpRayQueryTerminate:
2324 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2325 return false;
2326 case glslang::EOpRayQueryConfirmIntersection:
2327 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2328 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002329#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002330
2331 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002332 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002333 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002334 }
John Kessenich140f3df2015-06-26 16:58:36 -06002335}
2336
Jeff Bolz53134492019-06-25 13:31:10 -05002337// Construct a composite object, recursively copying members if their types don't match
2338spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2339{
2340 for (int c = 0; c < (int)constituents.size(); ++c) {
2341 spv::Id& constituent = constituents[c];
2342 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2343 spv::Id rType = builder.getTypeId(constituent);
2344 if (lType != rType) {
2345 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2346 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2347 } else if (builder.isStructType(rType)) {
2348 std::vector<spv::Id> rTypeConstituents;
2349 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2350 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002351 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2352 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002353 }
2354 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2355 } else {
2356 assert(builder.isArrayType(rType));
2357 std::vector<spv::Id> rTypeConstituents;
2358 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2359
2360 spv::Id elementRType = builder.getContainedTypeId(rType);
2361 for (int i = 0; i < numrTypeConstituents; ++i) {
2362 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2363 }
2364 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2365 }
2366 }
2367 }
2368 return builder.createCompositeConstruct(resultTypeId, constituents);
2369}
2370
John Kessenich140f3df2015-06-26 16:58:36 -06002371bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2372{
qining27e04a02016-04-14 16:40:20 -04002373 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2374 if (node->getType().getQualifier().isSpecConstant())
2375 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2376
John Kessenichfc51d282015-08-19 13:34:18 -06002377 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002378 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2379 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2380 // SPIR-V, for an out parameter
2381 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002382
John Kessenich8985fc92020-03-03 10:25:07 -07002383 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2384 invertedType :
2385 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002386
2387 // try texturing
2388 result = createImageTextureFunctionCall(node);
2389 if (result != spv::NoResult) {
2390 builder.clearAccessChain();
2391 builder.setAccessChainRValue(result);
2392
2393 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002394 }
2395#ifndef GLSLANG_WEB
2396 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002397 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002398 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002399 // "imageStore" is a special case, which has no result
2400 return false;
2401 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002402#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002403
John Kessenich140f3df2015-06-26 16:58:36 -06002404 glslang::TOperator binOp = glslang::EOpNull;
2405 bool reduceComparison = true;
2406 bool isMatrix = false;
2407 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002408 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002409
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002410 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2411
John Kessenich140f3df2015-06-26 16:58:36 -06002412 assert(node->getOp());
2413
John Kessenichf6640762016-08-01 19:44:00 -06002414 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002415
2416 switch (node->getOp()) {
2417 case glslang::EOpSequence:
2418 {
2419 if (preVisit)
2420 ++sequenceDepth;
2421 else
2422 --sequenceDepth;
2423
2424 if (sequenceDepth == 1) {
2425 // If this is the parent node of all the functions, we want to see them
2426 // early, so all call points have actual SPIR-V functions to reference.
2427 // In all cases, still let the traverser visit the children for us.
2428 makeFunctions(node->getAsAggregate()->getSequence());
2429
John Kessenich6fccb3c2016-09-19 16:01:41 -06002430 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002431 // anything else gets there, so visit out of order, doing them all now.
2432 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2433
John Kessenich6a60c2f2016-12-08 21:01:59 -07002434 // 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 -06002435 // so do them manually.
2436 visitFunctions(node->getAsAggregate()->getSequence());
2437
2438 return false;
2439 }
2440
2441 return true;
2442 }
2443 case glslang::EOpLinkerObjects:
2444 {
2445 if (visit == glslang::EvPreVisit)
2446 linkageOnly = true;
2447 else
2448 linkageOnly = false;
2449
2450 return true;
2451 }
2452 case glslang::EOpComma:
2453 {
2454 // processing from left to right naturally leaves the right-most
2455 // lying around in the access chain
2456 glslang::TIntermSequence& glslangOperands = node->getSequence();
2457 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2458 glslangOperands[i]->traverse(this);
2459
2460 return false;
2461 }
2462 case glslang::EOpFunction:
2463 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002464 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002465 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002466 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002467 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002468 } else {
2469 handleFunctionEntry(node);
2470 }
2471 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002472 if (inEntryPoint)
2473 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002474 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002475 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002476 }
2477
2478 return true;
2479 case glslang::EOpParameters:
2480 // Parameters will have been consumed by EOpFunction processing, but not
2481 // the body, so we still visited the function node's children, making this
2482 // child redundant.
2483 return false;
2484 case glslang::EOpFunctionCall:
2485 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002486 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002487 if (node->isUserDefined())
2488 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002489 if (result) {
2490 builder.clearAccessChain();
2491 builder.setAccessChainRValue(result);
2492 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002493 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002494
2495 return false;
2496 }
2497 case glslang::EOpConstructMat2x2:
2498 case glslang::EOpConstructMat2x3:
2499 case glslang::EOpConstructMat2x4:
2500 case glslang::EOpConstructMat3x2:
2501 case glslang::EOpConstructMat3x3:
2502 case glslang::EOpConstructMat3x4:
2503 case glslang::EOpConstructMat4x2:
2504 case glslang::EOpConstructMat4x3:
2505 case glslang::EOpConstructMat4x4:
2506 case glslang::EOpConstructDMat2x2:
2507 case glslang::EOpConstructDMat2x3:
2508 case glslang::EOpConstructDMat2x4:
2509 case glslang::EOpConstructDMat3x2:
2510 case glslang::EOpConstructDMat3x3:
2511 case glslang::EOpConstructDMat3x4:
2512 case glslang::EOpConstructDMat4x2:
2513 case glslang::EOpConstructDMat4x3:
2514 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002515 case glslang::EOpConstructIMat2x2:
2516 case glslang::EOpConstructIMat2x3:
2517 case glslang::EOpConstructIMat2x4:
2518 case glslang::EOpConstructIMat3x2:
2519 case glslang::EOpConstructIMat3x3:
2520 case glslang::EOpConstructIMat3x4:
2521 case glslang::EOpConstructIMat4x2:
2522 case glslang::EOpConstructIMat4x3:
2523 case glslang::EOpConstructIMat4x4:
2524 case glslang::EOpConstructUMat2x2:
2525 case glslang::EOpConstructUMat2x3:
2526 case glslang::EOpConstructUMat2x4:
2527 case glslang::EOpConstructUMat3x2:
2528 case glslang::EOpConstructUMat3x3:
2529 case glslang::EOpConstructUMat3x4:
2530 case glslang::EOpConstructUMat4x2:
2531 case glslang::EOpConstructUMat4x3:
2532 case glslang::EOpConstructUMat4x4:
2533 case glslang::EOpConstructBMat2x2:
2534 case glslang::EOpConstructBMat2x3:
2535 case glslang::EOpConstructBMat2x4:
2536 case glslang::EOpConstructBMat3x2:
2537 case glslang::EOpConstructBMat3x3:
2538 case glslang::EOpConstructBMat3x4:
2539 case glslang::EOpConstructBMat4x2:
2540 case glslang::EOpConstructBMat4x3:
2541 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002542 case glslang::EOpConstructF16Mat2x2:
2543 case glslang::EOpConstructF16Mat2x3:
2544 case glslang::EOpConstructF16Mat2x4:
2545 case glslang::EOpConstructF16Mat3x2:
2546 case glslang::EOpConstructF16Mat3x3:
2547 case glslang::EOpConstructF16Mat3x4:
2548 case glslang::EOpConstructF16Mat4x2:
2549 case glslang::EOpConstructF16Mat4x3:
2550 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002551 isMatrix = true;
2552 // fall through
2553 case glslang::EOpConstructFloat:
2554 case glslang::EOpConstructVec2:
2555 case glslang::EOpConstructVec3:
2556 case glslang::EOpConstructVec4:
2557 case glslang::EOpConstructDouble:
2558 case glslang::EOpConstructDVec2:
2559 case glslang::EOpConstructDVec3:
2560 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002561 case glslang::EOpConstructFloat16:
2562 case glslang::EOpConstructF16Vec2:
2563 case glslang::EOpConstructF16Vec3:
2564 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002565 case glslang::EOpConstructBool:
2566 case glslang::EOpConstructBVec2:
2567 case glslang::EOpConstructBVec3:
2568 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002569 case glslang::EOpConstructInt8:
2570 case glslang::EOpConstructI8Vec2:
2571 case glslang::EOpConstructI8Vec3:
2572 case glslang::EOpConstructI8Vec4:
2573 case glslang::EOpConstructUint8:
2574 case glslang::EOpConstructU8Vec2:
2575 case glslang::EOpConstructU8Vec3:
2576 case glslang::EOpConstructU8Vec4:
2577 case glslang::EOpConstructInt16:
2578 case glslang::EOpConstructI16Vec2:
2579 case glslang::EOpConstructI16Vec3:
2580 case glslang::EOpConstructI16Vec4:
2581 case glslang::EOpConstructUint16:
2582 case glslang::EOpConstructU16Vec2:
2583 case glslang::EOpConstructU16Vec3:
2584 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002585 case glslang::EOpConstructInt:
2586 case glslang::EOpConstructIVec2:
2587 case glslang::EOpConstructIVec3:
2588 case glslang::EOpConstructIVec4:
2589 case glslang::EOpConstructUint:
2590 case glslang::EOpConstructUVec2:
2591 case glslang::EOpConstructUVec3:
2592 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002593 case glslang::EOpConstructInt64:
2594 case glslang::EOpConstructI64Vec2:
2595 case glslang::EOpConstructI64Vec3:
2596 case glslang::EOpConstructI64Vec4:
2597 case glslang::EOpConstructUint64:
2598 case glslang::EOpConstructU64Vec2:
2599 case glslang::EOpConstructU64Vec3:
2600 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002601 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002602 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002603 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002604 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002605 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002606 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002607 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002608 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002609 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002610 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002611 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002612 else if (node->getOp() == glslang::EOpConstructStruct ||
2613 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2614 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002615 std::vector<spv::Id> constituents;
2616 for (int c = 0; c < (int)arguments.size(); ++c)
2617 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002618 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002619 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002620 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002621 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002622 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002623
2624 builder.clearAccessChain();
2625 builder.setAccessChainRValue(constructed);
2626
2627 return false;
2628 }
2629
2630 // These six are component-wise compares with component-wise results.
2631 // Forward on to createBinaryOperation(), requesting a vector result.
2632 case glslang::EOpLessThan:
2633 case glslang::EOpGreaterThan:
2634 case glslang::EOpLessThanEqual:
2635 case glslang::EOpGreaterThanEqual:
2636 case glslang::EOpVectorEqual:
2637 case glslang::EOpVectorNotEqual:
2638 {
2639 // Map the operation to a binary
2640 binOp = node->getOp();
2641 reduceComparison = false;
2642 switch (node->getOp()) {
2643 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2644 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2645 default: binOp = node->getOp(); break;
2646 }
2647
2648 break;
2649 }
2650 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002651 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002652 binOp = glslang::EOpMul;
2653 break;
2654 case glslang::EOpOuterProduct:
2655 // two vectors multiplied to make a matrix
2656 binOp = glslang::EOpOuterProduct;
2657 break;
2658 case glslang::EOpDot:
2659 {
qining25262b32016-05-06 17:25:16 -04002660 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002661 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002662 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002663 binOp = glslang::EOpMul;
2664 break;
2665 }
2666 case glslang::EOpMod:
2667 // when an aggregate, this is the floating-point mod built-in function,
2668 // which can be emitted by the one in createBinaryOperation()
2669 binOp = glslang::EOpMod;
2670 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002671
John Kessenich140f3df2015-06-26 16:58:36 -06002672 case glslang::EOpEmitVertex:
2673 case glslang::EOpEndPrimitive:
2674 case glslang::EOpBarrier:
2675 case glslang::EOpMemoryBarrier:
2676 case glslang::EOpMemoryBarrierAtomicCounter:
2677 case glslang::EOpMemoryBarrierBuffer:
2678 case glslang::EOpMemoryBarrierImage:
2679 case glslang::EOpMemoryBarrierShared:
2680 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002681 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002682 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002683 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002684 case glslang::EOpWorkgroupMemoryBarrier:
2685 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002686 case glslang::EOpSubgroupBarrier:
2687 case glslang::EOpSubgroupMemoryBarrier:
2688 case glslang::EOpSubgroupMemoryBarrierBuffer:
2689 case glslang::EOpSubgroupMemoryBarrierImage:
2690 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002691 noReturnValue = true;
2692 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2693 break;
2694
John Kessenich426394d2015-07-23 10:22:48 -06002695 case glslang::EOpAtomicAdd:
2696 case glslang::EOpAtomicMin:
2697 case glslang::EOpAtomicMax:
2698 case glslang::EOpAtomicAnd:
2699 case glslang::EOpAtomicOr:
2700 case glslang::EOpAtomicXor:
2701 case glslang::EOpAtomicExchange:
2702 case glslang::EOpAtomicCompSwap:
2703 atomic = true;
2704 break;
2705
John Kesseniche5eee8f2019-10-18 01:03:11 -06002706#ifndef GLSLANG_WEB
2707 case glslang::EOpAtomicStore:
2708 noReturnValue = true;
2709 // fallthrough
2710 case glslang::EOpAtomicLoad:
2711 atomic = true;
2712 break;
2713
John Kessenich0d0c6d32017-07-23 16:08:26 -06002714 case glslang::EOpAtomicCounterAdd:
2715 case glslang::EOpAtomicCounterSubtract:
2716 case glslang::EOpAtomicCounterMin:
2717 case glslang::EOpAtomicCounterMax:
2718 case glslang::EOpAtomicCounterAnd:
2719 case glslang::EOpAtomicCounterOr:
2720 case glslang::EOpAtomicCounterXor:
2721 case glslang::EOpAtomicCounterExchange:
2722 case glslang::EOpAtomicCounterCompSwap:
2723 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2724 builder.addCapability(spv::CapabilityAtomicStorageOps);
2725 atomic = true;
2726 break;
2727
Ian Romanickb3bd4022019-01-21 08:57:25 -08002728 case glslang::EOpAbsDifference:
2729 case glslang::EOpAddSaturate:
2730 case glslang::EOpSubSaturate:
2731 case glslang::EOpAverage:
2732 case glslang::EOpAverageRounded:
2733 case glslang::EOpMul32x16:
2734 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2735 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2736 binOp = node->getOp();
2737 break;
2738
Daniel Kochdb32b242020-03-17 20:42:47 -04002739 case glslang::EOpIgnoreIntersection:
2740 case glslang::EOpTerminateRay:
2741 case glslang::EOpTrace:
2742 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002743 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2744 noReturnValue = true;
2745 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002746 case glslang::EOpRayQueryInitialize:
2747 case glslang::EOpRayQueryTerminate:
2748 case glslang::EOpRayQueryGenerateIntersection:
2749 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002750 builder.addExtension("SPV_KHR_ray_query");
2751 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002752 noReturnValue = true;
2753 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002754 case glslang::EOpRayQueryProceed:
2755 case glslang::EOpRayQueryGetIntersectionType:
2756 case glslang::EOpRayQueryGetRayTMin:
2757 case glslang::EOpRayQueryGetRayFlags:
2758 case glslang::EOpRayQueryGetIntersectionT:
2759 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2760 case glslang::EOpRayQueryGetIntersectionInstanceId:
2761 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2762 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2763 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2764 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2765 case glslang::EOpRayQueryGetIntersectionFrontFace:
2766 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2767 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2768 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2769 case glslang::EOpRayQueryGetWorldRayDirection:
2770 case glslang::EOpRayQueryGetWorldRayOrigin:
2771 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2772 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2773 builder.addExtension("SPV_KHR_ray_query");
2774 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2775 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002776 case glslang::EOpCooperativeMatrixLoad:
2777 case glslang::EOpCooperativeMatrixStore:
2778 noReturnValue = true;
2779 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002780 case glslang::EOpBeginInvocationInterlock:
2781 case glslang::EOpEndInvocationInterlock:
2782 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2783 noReturnValue = true;
2784 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002785#endif
Chao Chen3c366992018-09-19 11:41:59 -07002786
Jeff Bolz04d73732019-05-31 13:06:01 -05002787 case glslang::EOpDebugPrintf:
2788 noReturnValue = true;
2789 break;
2790
John Kessenich140f3df2015-06-26 16:58:36 -06002791 default:
2792 break;
2793 }
2794
2795 //
2796 // See if it maps to a regular operation.
2797 //
John Kessenich140f3df2015-06-26 16:58:36 -06002798 if (binOp != glslang::EOpNull) {
2799 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2800 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2801 assert(left && right);
2802
2803 builder.clearAccessChain();
2804 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002805 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002806
2807 builder.clearAccessChain();
2808 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002809 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002810
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002811 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002812 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002813 TranslateNoContractionDecoration(node->getType().getQualifier()),
2814 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002815 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002816 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002817 left->getType().getBasicType(), reduceComparison);
2818
2819 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002820 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002821 builder.clearAccessChain();
2822 builder.setAccessChainRValue(result);
2823
2824 return false;
2825 }
2826
John Kessenich426394d2015-07-23 10:22:48 -06002827 //
2828 // Create the list of operands.
2829 //
John Kessenich140f3df2015-06-26 16:58:36 -06002830 glslang::TIntermSequence& glslangOperands = node->getSequence();
2831 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002832 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002833 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002834 // special case l-value operands; there are just a few
2835 bool lvalue = false;
2836 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002837 case glslang::EOpModf:
2838 if (arg == 1)
2839 lvalue = true;
2840 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002841
Torosdagli06c2eee2020-03-19 11:09:57 -04002842 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002843 case glslang::EOpRayQueryTerminate:
2844 case glslang::EOpRayQueryConfirmIntersection:
2845 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002846 case glslang::EOpRayQueryGenerateIntersection:
2847 case glslang::EOpRayQueryGetIntersectionType:
2848 case glslang::EOpRayQueryGetIntersectionT:
2849 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2850 case glslang::EOpRayQueryGetIntersectionInstanceId:
2851 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2852 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2853 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2854 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2855 case glslang::EOpRayQueryGetIntersectionFrontFace:
2856 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2857 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2858 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2859 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2860 if (arg == 0)
2861 lvalue = true;
2862 break;
2863
John Kesseniche5eee8f2019-10-18 01:03:11 -06002864 case glslang::EOpAtomicAdd:
2865 case glslang::EOpAtomicMin:
2866 case glslang::EOpAtomicMax:
2867 case glslang::EOpAtomicAnd:
2868 case glslang::EOpAtomicOr:
2869 case glslang::EOpAtomicXor:
2870 case glslang::EOpAtomicExchange:
2871 case glslang::EOpAtomicCompSwap:
2872 if (arg == 0)
2873 lvalue = true;
2874 break;
2875
John Kessenicha28f7a72019-08-06 07:00:58 -06002876#ifndef GLSLANG_WEB
2877 case glslang::EOpFrexp:
2878 if (arg == 1)
2879 lvalue = true;
2880 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002881 case glslang::EOpInterpolateAtSample:
2882 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002883 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002884 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002885 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002886
2887 // Does it need a swizzle inversion? If so, evaluation is inverted;
2888 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002889 // That is, we transform
2890 //
2891 // interpolate(v.zy) -> interpolate(v).zy
2892 //
John Kessenichecba76f2017-01-06 00:34:48 -07002893 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002894 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002895 invertedType = convertGlslangToSpvType(
2896 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002897 }
Rex Xu7a26c172015-12-08 17:12:09 +08002898 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002899 case glslang::EOpAtomicLoad:
2900 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002901 case glslang::EOpAtomicCounterAdd:
2902 case glslang::EOpAtomicCounterSubtract:
2903 case glslang::EOpAtomicCounterMin:
2904 case glslang::EOpAtomicCounterMax:
2905 case glslang::EOpAtomicCounterAnd:
2906 case glslang::EOpAtomicCounterOr:
2907 case glslang::EOpAtomicCounterXor:
2908 case glslang::EOpAtomicCounterExchange:
2909 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002910 if (arg == 0)
2911 lvalue = true;
2912 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002913 case glslang::EOpAddCarry:
2914 case glslang::EOpSubBorrow:
2915 if (arg == 2)
2916 lvalue = true;
2917 break;
2918 case glslang::EOpUMulExtended:
2919 case glslang::EOpIMulExtended:
2920 if (arg >= 2)
2921 lvalue = true;
2922 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002923 case glslang::EOpCooperativeMatrixLoad:
2924 if (arg == 0 || arg == 1)
2925 lvalue = true;
2926 break;
2927 case glslang::EOpCooperativeMatrixStore:
2928 if (arg == 1)
2929 lvalue = true;
2930 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002931#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002932 default:
2933 break;
2934 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002935 builder.clearAccessChain();
2936 if (invertedType != spv::NoType && arg == 0)
2937 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2938 else
2939 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002940
John Kessenichb9197c82019-08-11 07:41:45 -06002941#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002942 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2943 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2944
2945 if (arg == 1) {
2946 // fold "element" parameter into the access chain
2947 spv::Builder::AccessChain save = builder.getAccessChain();
2948 builder.clearAccessChain();
2949 glslangOperands[2]->traverse(this);
2950
2951 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2952
2953 builder.setAccessChain(save);
2954
2955 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002956 builder.accessChainPush(elementId,
2957 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2958 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002959
2960 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2961 unsigned int alignment = builder.getAccessChain().alignment;
2962
2963 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2964 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2965 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2966 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2967 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002968 if (builder.getStorageClass(builder.getAccessChain().base) ==
2969 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002970 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2971 }
2972
2973 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2974
2975 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2976 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2977 }
2978
John Kessenich8985fc92020-03-03 10:25:07 -07002979 if (memoryAccess &
2980 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2981 memoryAccessOperands.push_back(spv::IdImmediate(true,
2982 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002983 }
2984 } else if (arg == 2) {
2985 continue;
2986 }
2987 }
John Kessenichb9197c82019-08-11 07:41:45 -06002988#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002989
John Kessenichbbbd9a22020-03-03 07:21:37 -07002990 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002991 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002992 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2993 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2994 // reduce to a simple access chain. So, we need a temporary vector to
2995 // receive the result, and must later swizzle that into the original
2996 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06002997 complexLvalues.push_back(builder.getAccessChain());
John Kessenich435dd802020-06-30 01:27:08 -06002998 temporaryLvalues.push_back(builder.createVariable(
2999 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003000 builder.accessChainGetInferredType(), "swizzleTemp"));
3001 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003002 } else {
3003 operands.push_back(builder.accessChainGetLValue());
3004 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003005 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3006 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3007 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003008 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003009 glslang::TOperator glslangOp = node->getOp();
3010 if (arg == 1 &&
3011 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3012 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3013 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3014 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3015 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3016 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3017 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3018 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3019 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3020 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3021 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3022 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3023 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3024 )) {
3025 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3026 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3027 }
3028 else {
3029 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3030 }
3031
John Kesseniche485c7a2017-05-31 18:50:53 -06003032 }
John Kessenich140f3df2015-06-26 16:58:36 -06003033 }
John Kessenich426394d2015-07-23 10:22:48 -06003034
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003035 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003036#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003037 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3038 std::vector<spv::IdImmediate> idImmOps;
3039
3040 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3041 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3042 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3043 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3044 // get the pointee type
3045 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3046 assert(builder.isCooperativeMatrixType(typeId));
3047 // do the op
3048 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3049 // store the result to the pointer (out param 'm')
3050 builder.createStore(result, operands[0]);
3051 result = 0;
3052 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3053 std::vector<spv::IdImmediate> idImmOps;
3054
3055 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3056 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3057 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3058 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3059 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3060
3061 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3062 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003063 } else
3064#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003065 if (atomic) {
3066 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003067 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3068 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003069 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3070 if (!nonSemanticDebugPrintf) {
3071 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3072 }
3073 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3074 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003075 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003076 // Pass through to generic operations.
3077 switch (glslangOperands.size()) {
3078 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003079 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003080 break;
3081 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003082 {
3083 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003084 TranslateNoContractionDecoration(node->getType().getQualifier()),
3085 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003086 result = createUnaryOperation(
3087 node->getOp(), decorations,
3088 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003089 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003090 }
John Kessenich426394d2015-07-23 10:22:48 -06003091 break;
3092 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003093 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003094 break;
3095 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003096
John Kessenichbbbd9a22020-03-03 07:21:37 -07003097 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003098 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003099
3100 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3101 builder.setAccessChain(complexLvalues[i]);
John Kessenich435dd802020-06-30 01:27:08 -06003102 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003103 }
John Kessenich140f3df2015-06-26 16:58:36 -06003104 }
3105
3106 if (noReturnValue)
3107 return false;
3108
3109 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003110 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003111 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003112 } else {
3113 builder.clearAccessChain();
3114 builder.setAccessChainRValue(result);
3115 return false;
3116 }
3117}
3118
John Kessenich433e9ff2017-01-26 20:31:11 -07003119// This path handles both if-then-else and ?:
3120// The if-then-else has a node type of void, while
3121// ?: has either a void or a non-void node type
3122//
3123// Leaving the result, when not void:
3124// GLSL only has r-values as the result of a :?, but
3125// if we have an l-value, that can be more efficient if it will
3126// become the base of a complex r-value expression, because the
3127// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003128bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3129{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003130 // see if OpSelect can handle it
3131 const auto isOpSelectable = [&]() {
3132 if (node->getBasicType() == glslang::EbtVoid)
3133 return false;
3134 // OpSelect can do all other types starting with SPV 1.4
3135 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3136 // pre-1.4, only scalars and vectors can be handled
3137 if ((!node->getType().isScalar() && !node->getType().isVector()))
3138 return false;
3139 }
3140 return true;
3141 };
3142
John Kessenich4bee5312018-02-20 21:29:05 -07003143 // See if it simple and safe, or required, to execute both sides.
3144 // Crucially, side effects must be either semantically required or avoided,
3145 // and there are performance trade-offs.
3146 // Return true if required or a good idea (and safe) to execute both sides,
3147 // false otherwise.
3148 const auto bothSidesPolicy = [&]() -> bool {
3149 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003150 if (node->getTrueBlock() == nullptr ||
3151 node->getFalseBlock() == nullptr)
3152 return false;
3153
John Kessenich4bee5312018-02-20 21:29:05 -07003154 // required? (unless we write additional code to look for side effects
3155 // and make performance trade-offs if none are present)
3156 if (!node->getShortCircuit())
3157 return true;
3158
3159 // if not required to execute both, decide based on performance/practicality...
3160
John Kessenich0c1e71a2019-01-10 18:23:06 +07003161 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003162 return false;
3163
John Kessenich433e9ff2017-01-26 20:31:11 -07003164 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3165 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3166
3167 // return true if a single operand to ? : is okay for OpSelect
3168 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003169 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003170 };
3171
3172 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3173 operandOkay(node->getFalseBlock()->getAsTyped());
3174 };
3175
John Kessenich4bee5312018-02-20 21:29:05 -07003176 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3177 // emit the condition before doing anything with selection
3178 node->getCondition()->traverse(this);
3179 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3180
3181 // Find a way of executing both sides and selecting the right result.
3182 const auto executeBothSides = [&]() -> void {
3183 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003184 node->getTrueBlock()->traverse(this);
3185 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3186 node->getFalseBlock()->traverse(this);
3187 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3188
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003189 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003190
John Kessenich4bee5312018-02-20 21:29:05 -07003191 // done if void
3192 if (node->getBasicType() == glslang::EbtVoid)
3193 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003194
John Kessenich4bee5312018-02-20 21:29:05 -07003195 // emit code to select between trueValue and falseValue
3196
3197 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003198 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003199 // Emit OpSelect for this selection.
3200
3201 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003202 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3203 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003204 condition = builder.smearScalar(spv::NoPrecision, condition,
3205 builder.makeVectorType(builder.makeBoolType(),
3206 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003207 }
John Kessenich4bee5312018-02-20 21:29:05 -07003208
3209 // OpSelect
3210 result = builder.createTriOp(spv::OpSelect,
3211 convertGlslangToSpvType(node->getType()), condition,
3212 trueValue, falseValue);
3213
3214 builder.clearAccessChain();
3215 builder.setAccessChainRValue(result);
3216 } else {
3217 // We need control flow to select the result.
3218 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003219 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3220 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003221
3222 // Selection control:
3223 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3224
3225 // make an "if" based on the value created by the condition
3226 spv::Builder::If ifBuilder(condition, control, builder);
3227
3228 // emit the "then" statement
3229 builder.createStore(trueValue, result);
3230 ifBuilder.makeBeginElse();
3231 // emit the "else" statement
3232 builder.createStore(falseValue, result);
3233
3234 // finish off the control flow
3235 ifBuilder.makeEndIf();
3236
3237 builder.clearAccessChain();
3238 builder.setAccessChainLValue(result);
3239 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003240 };
3241
John Kessenich4bee5312018-02-20 21:29:05 -07003242 // Execute the one side needed, as per the condition
3243 const auto executeOneSide = [&]() {
3244 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003245 if (node->getBasicType() != glslang::EbtVoid) {
3246 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3247 convertGlslangToSpvType(node->getType()));
3248 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003249
John Kessenich4bee5312018-02-20 21:29:05 -07003250 // Selection control:
3251 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3252
3253 // make an "if" based on the value created by the condition
3254 spv::Builder::If ifBuilder(condition, control, builder);
3255
3256 // emit the "then" statement
3257 if (node->getTrueBlock() != nullptr) {
3258 node->getTrueBlock()->traverse(this);
3259 if (result != spv::NoResult)
3260 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3261 }
3262
3263 if (node->getFalseBlock() != nullptr) {
3264 ifBuilder.makeBeginElse();
3265 // emit the "else" statement
3266 node->getFalseBlock()->traverse(this);
3267 if (result != spv::NoResult)
3268 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3269 }
3270
3271 // finish off the control flow
3272 ifBuilder.makeEndIf();
3273
3274 if (result != spv::NoResult) {
3275 builder.clearAccessChain();
3276 builder.setAccessChainLValue(result);
3277 }
3278 };
3279
3280 // Try for OpSelect (or a requirement to execute both sides)
3281 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003282 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3283 if (node->getType().getQualifier().isSpecConstant())
3284 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003285 executeBothSides();
3286 } else
3287 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003288
3289 return false;
3290}
3291
3292bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3293{
3294 // emit and get the condition before doing anything with switch
3295 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003296 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003297
Rex Xu57e65922017-07-04 23:23:40 +08003298 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003299 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003300
John Kessenich140f3df2015-06-26 16:58:36 -06003301 // browse the children to sort out code segments
3302 int defaultSegment = -1;
3303 std::vector<TIntermNode*> codeSegments;
3304 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3305 std::vector<int> caseValues;
3306 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3307 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3308 TIntermNode* child = *c;
3309 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003310 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003311 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003312 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003313 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3314 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003315 } else
3316 codeSegments.push_back(child);
3317 }
3318
qining25262b32016-05-06 17:25:16 -04003319 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003320 // statements between the last case and the end of the switch statement
3321 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3322 (int)codeSegments.size() == defaultSegment)
3323 codeSegments.push_back(nullptr);
3324
3325 // make the switch statement
3326 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003327 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3328 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003329
3330 // emit all the code in the segments
3331 breakForLoop.push(false);
3332 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3333 builder.nextSwitchSegment(segmentBlocks, s);
3334 if (codeSegments[s])
3335 codeSegments[s]->traverse(this);
3336 else
3337 builder.addSwitchBreak();
3338 }
3339 breakForLoop.pop();
3340
3341 builder.endSwitch(segmentBlocks);
3342
3343 return false;
3344}
3345
3346void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3347{
3348 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003349 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003350
3351 builder.clearAccessChain();
3352 builder.setAccessChainRValue(constant);
3353}
3354
3355bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3356{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003357 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003358 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003359
3360 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003361 std::vector<unsigned int> operands;
3362 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003363
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003364 // Spec requires back edges to target header blocks, and every header block
3365 // must dominate its merge block. Make a header block first to ensure these
3366 // conditions are met. By definition, it will contain OpLoopMerge, followed
3367 // by a block-ending branch. But we don't want to put any other body/test
3368 // instructions in it, since the body/test may have arbitrary instructions,
3369 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003370 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003371 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003372 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003373 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003374 spv::Block& test = builder.makeNewBlock();
3375 builder.createBranch(&test);
3376
3377 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003378 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003379 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003380 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3381
3382 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003383 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003384 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003385 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003386 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003387 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003388
3389 builder.setBuildPoint(&blocks.continue_target);
3390 if (node->getTerminal())
3391 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003392 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003393 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003394 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003395 builder.createBranch(&blocks.body);
3396
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003397 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003398 builder.setBuildPoint(&blocks.body);
3399 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003400 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003401 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003402 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003403
3404 builder.setBuildPoint(&blocks.continue_target);
3405 if (node->getTerminal())
3406 node->getTerminal()->traverse(this);
3407 if (node->getTest()) {
3408 node->getTest()->traverse(this);
3409 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003410 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003411 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003412 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003413 // TODO: unless there was a break/return/discard instruction
3414 // somewhere in the body, this is an infinite loop, so we should
3415 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003416 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003417 }
John Kessenich140f3df2015-06-26 16:58:36 -06003418 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003419 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003420 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003421 return false;
3422}
3423
3424bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3425{
3426 if (node->getExpression())
3427 node->getExpression()->traverse(this);
3428
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003429 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003430
John Kessenich140f3df2015-06-26 16:58:36 -06003431 switch (node->getFlowOp()) {
3432 case glslang::EOpKill:
3433 builder.makeDiscard();
3434 break;
3435 case glslang::EOpBreak:
3436 if (breakForLoop.top())
3437 builder.createLoopExit();
3438 else
3439 builder.addSwitchBreak();
3440 break;
3441 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003442 builder.createLoopContinue();
3443 break;
3444 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003445 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003446 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3447 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003448 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3449 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003450 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003451 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3452 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003453 builder.setAccessChainLValue(copyId);
3454 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003455 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003456 }
3457 builder.makeReturn(false, returnId);
3458 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003459 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003460
3461 builder.clearAccessChain();
3462 break;
3463
John Kessenichb9197c82019-08-11 07:41:45 -06003464#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003465 case glslang::EOpDemote:
3466 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3467 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3468 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3469 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003470#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003471
John Kessenich140f3df2015-06-26 16:58:36 -06003472 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003473 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003474 break;
3475 }
3476
3477 return false;
3478}
3479
John Kessenich9c14f772019-06-17 08:38:35 -06003480spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003481{
qining25262b32016-05-06 17:25:16 -04003482 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003483 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003484 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003485 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003486 spv::Id result = createSpvConstant(*node);
3487 if (result != spv::NoResult)
3488 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003489 }
3490
3491 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003492 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003493 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3494 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003495
John Kessenichb9197c82019-08-11 07:41:45 -06003496 const bool contains16BitType = node->getType().contains16BitFloat() ||
3497 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003498 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003499 switch (storageClass) {
3500 case spv::StorageClassInput:
3501 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003502 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003503 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003504 break;
John Kessenich18310872018-05-14 22:08:53 -06003505 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003506 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003507 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3508 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003509 else
3510 builder.addCapability(spv::CapabilityStorageUniform16);
3511 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003512#ifndef GLSLANG_WEB
3513 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003514 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003515 builder.addCapability(spv::CapabilityStoragePushConstant16);
3516 break;
John Kessenich18310872018-05-14 22:08:53 -06003517 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003518 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003519 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003520 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3521 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003522#endif
John Kessenich18310872018-05-14 22:08:53 -06003523 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003524 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003525 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003526 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003527 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003528 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003529 }
3530 }
Rex Xuf89ad982017-04-07 23:22:33 +08003531
John Kessenichb9197c82019-08-11 07:41:45 -06003532 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003533 if (storageClass == spv::StorageClassPushConstant) {
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::CapabilityStoragePushConstant8);
3536 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003537 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003538 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003539 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003540 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003541 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003542 } else {
3543 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003544 }
3545 }
3546
John Kessenich140f3df2015-06-26 16:58:36 -06003547 const char* name = node->getName().c_str();
3548 if (glslang::IsAnonymous(name))
3549 name = "";
3550
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003551 spv::Id initializer = spv::NoResult;
3552
3553 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3554 !node->getConstArray().empty()) {
3555 int nextConst = 0;
3556 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3557 node->getConstArray(),
3558 nextConst,
3559 false /* specConst */);
3560 }
3561
John Kessenich435dd802020-06-30 01:27:08 -06003562 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003563}
3564
3565// Return type Id of the sampled type.
3566spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3567{
3568 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003569 case glslang::EbtInt: return builder.makeIntType(32);
3570 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003571 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003572#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003573 case glslang::EbtFloat16:
3574 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3575 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3576 return builder.makeFloatType(16);
3577#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003578 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003579 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003580 return builder.makeFloatType(32);
3581 }
3582}
3583
John Kessenich8c8505c2016-07-26 12:50:38 -06003584// If node is a swizzle operation, return the type that should be used if
3585// the swizzle base is first consumed by another operation, before the swizzle
3586// is applied.
3587spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3588{
John Kessenichecba76f2017-01-06 00:34:48 -07003589 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003590 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3591 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3592 else
3593 return spv::NoType;
3594}
3595
3596// When inverting a swizzle with a parent op, this function
3597// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003598spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3599 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003600{
3601 std::vector<unsigned> swizzle;
3602 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3603 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3604}
3605
John Kessenich8c8505c2016-07-26 12:50:38 -06003606// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3607void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3608{
3609 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3610 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3611 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3612}
3613
John Kessenich3ac051e2015-12-20 11:29:16 -07003614// Convert from a glslang type to an SPV type, by calling into a
3615// recursive version of this function. This establishes the inherited
3616// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003617spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003618{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003619 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003620}
3621
3622// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003623// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003624// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003625spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003626 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3627 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003628{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003629 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003630
3631 switch (type.getBasicType()) {
3632 case glslang::EbtVoid:
3633 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003634 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003635 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003636 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003637 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3638 // a 32-bit int where non-0 means true.
3639 if (explicitLayout != glslang::ElpNone)
3640 spvType = builder.makeUintType(32);
3641 else
3642 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003643 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003644 case glslang::EbtInt:
3645 spvType = builder.makeIntType(32);
3646 break;
3647 case glslang::EbtUint:
3648 spvType = builder.makeUintType(32);
3649 break;
3650 case glslang::EbtFloat:
3651 spvType = builder.makeFloatType(32);
3652 break;
3653#ifndef GLSLANG_WEB
3654 case glslang::EbtDouble:
3655 spvType = builder.makeFloatType(64);
3656 break;
3657 case glslang::EbtFloat16:
3658 spvType = builder.makeFloatType(16);
3659 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003660 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003661 spvType = builder.makeIntType(8);
3662 break;
3663 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003664 spvType = builder.makeUintType(8);
3665 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003666 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003667 spvType = builder.makeIntType(16);
3668 break;
3669 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003670 spvType = builder.makeUintType(16);
3671 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003672 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003673 spvType = builder.makeIntType(64);
3674 break;
3675 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003676 spvType = builder.makeUintType(64);
3677 break;
John Kessenich426394d2015-07-23 10:22:48 -06003678 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003679 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003680 spvType = builder.makeUintType(32);
3681 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003682 case glslang::EbtAccStruct:
3683 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003684 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003685 case glslang::EbtRayQuery:
3686 spvType = builder.makeRayQueryType();
3687 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003688 case glslang::EbtReference:
3689 {
3690 // Make the forward pointer, then recurse to convert the structure type, then
3691 // patch up the forward pointer with a real pointer type.
3692 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3693 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3694 forwardPointers[type.getReferentType()] = forwardId;
3695 }
3696 spvType = forwardPointers[type.getReferentType()];
3697 if (!forwardReferenceOnly) {
3698 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3699 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3700 forwardPointers[type.getReferentType()],
3701 referentType);
3702 }
3703 }
3704 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003705#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003706 case glslang::EbtSampler:
3707 {
3708 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003709 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003710 spvType = builder.makeSamplerType();
3711 } else {
3712 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003713 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3714 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3715 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3716 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003717 // already has both image and sampler, make the combined type
3718 spvType = builder.makeSampledImageType(spvType);
3719 }
John Kessenich55e7d112015-11-15 21:33:39 -07003720 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003721 }
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723 case glslang::EbtStruct:
3724 case glslang::EbtBlock:
3725 {
3726 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003727 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003728
3729 // Try to share structs for different layouts, but not yet for other
3730 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003731 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003732 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003733 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003734 break;
3735
3736 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003737 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003738 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003739 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003740 }
3741 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003742 case glslang::EbtString:
3743 // no type used for OpString
3744 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003745 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003746 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003747 break;
3748 }
3749
3750 if (type.isMatrix())
3751 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3752 else {
3753 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3754 if (type.getVectorSize() > 1)
3755 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3756 }
3757
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003758 if (type.isCoopMat()) {
3759 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3760 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3761 if (type.getBasicType() == glslang::EbtFloat16)
3762 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003763 if (type.getBasicType() == glslang::EbtUint8 ||
3764 type.getBasicType() == glslang::EbtInt8) {
3765 builder.addCapability(spv::CapabilityInt8);
3766 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003767
3768 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3769 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3770 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3771
3772 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3773 }
3774
John Kessenich140f3df2015-06-26 16:58:36 -06003775 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003776 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3777
John Kessenichc9a80832015-09-12 12:17:44 -06003778 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003779 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003780 // We need to decorate array strides for types needing explicit layout, except blocks.
3781 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003782 // Use a dummy glslang type for querying internal strides of
3783 // arrays of arrays, but using just a one-dimensional array.
3784 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003785 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3786 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003787
3788 // Will compute the higher-order strides here, rather than making a whole
3789 // pile of types and doing repetitive recursion on their contents.
3790 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3791 }
John Kessenichf8842e52016-01-04 19:22:56 -07003792
3793 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003794 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003795 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003796 if (stride > 0)
3797 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003798 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003799 }
3800 } else {
3801 // single-dimensional array, and don't yet have stride
3802
John Kessenichf8842e52016-01-04 19:22:56 -07003803 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003804 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3805 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003806 }
John Kessenich31ed4832015-09-09 17:51:38 -06003807
John Kessenichead86222018-03-28 18:01:20 -06003808 // Do the outer dimension, which might not be known for a runtime-sized array.
3809 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3810 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003811 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003812 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003813#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003814 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003815 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003816 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3817 }
John Kessenichb9197c82019-08-11 07:41:45 -06003818#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003819 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003820 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003821 if (stride > 0)
3822 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003823 }
3824
3825 return spvType;
3826}
3827
John Kessenich0e737842017-03-24 18:38:16 -06003828// TODO: this functionality should exist at a higher level, in creating the AST
3829//
3830// Identify interface members that don't have their required extension turned on.
3831//
3832bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3833{
John Kessenicha28f7a72019-08-06 07:00:58 -06003834#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003835 auto& extensions = glslangIntermediate->getRequestedExtensions();
3836
Rex Xubcf291a2017-03-29 23:01:36 +08003837 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3838 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3839 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003840 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3841 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3842 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003843
3844 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3845 if (member.getFieldName() == "gl_ViewportMask" &&
3846 extensions.find("GL_NV_viewport_array2") == extensions.end())
3847 return true;
3848 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3849 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3850 return true;
3851 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3852 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3853 return true;
3854 }
3855#endif
John Kessenich0e737842017-03-24 18:38:16 -06003856
3857 return false;
3858};
3859
John Kessenich6090df02016-06-30 21:18:02 -06003860// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3861// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3862// Mutually recursive with convertGlslangToSpvType().
3863spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3864 const glslang::TTypeList* glslangMembers,
3865 glslang::TLayoutPacking explicitLayout,
3866 const glslang::TQualifier& qualifier)
3867{
3868 // Create a vector of struct types for SPIR-V to consume
3869 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003870 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3871 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003872 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003873 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3874 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3875 if (glslangMember.hiddenMember()) {
3876 ++memberDelta;
3877 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003878 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003879 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003880 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003881 if (filterMember(glslangMember)) {
3882 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003883 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003884 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003885 }
Roy05a5b532020-01-03 16:21:34 +08003886 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003887 }
John Kessenich6090df02016-06-30 21:18:02 -06003888 // modify just this child's view of the qualifier
3889 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3890 InheritQualifiers(memberQualifier, qualifier);
3891
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003892 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003893 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003894 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003895
3896 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003897 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3898 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003899
3900 // Make forward pointers for any pointer members, and create a list of members to
3901 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003902 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003903 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3904 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3905 }
3906 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003907 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3908 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003909 } else {
3910 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003911 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3912 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003913 }
John Kessenich6090df02016-06-30 21:18:02 -06003914 }
3915 }
3916
3917 // Make the SPIR-V type
3918 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003919 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003920 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3921
3922 // Decorate it
3923 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3924
John Kessenichd72f4882019-01-16 14:55:37 +07003925 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003926 auto it = deferredForwardPointers[i];
3927 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3928 }
3929
John Kessenich6090df02016-06-30 21:18:02 -06003930 return spvType;
3931}
3932
3933void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3934 const glslang::TTypeList* glslangMembers,
3935 glslang::TLayoutPacking explicitLayout,
3936 const glslang::TQualifier& qualifier,
3937 spv::Id spvType)
3938{
3939 // Name and decorate the non-hidden members
3940 int offset = -1;
3941 int locationOffset = 0; // for use within the members of this struct
3942 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3943 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3944 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003945 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003946 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003947 if (filterMember(glslangMember))
3948 continue;
3949 }
John Kessenich6090df02016-06-30 21:18:02 -06003950
3951 // modify just this child's view of the qualifier
3952 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3953 InheritQualifiers(memberQualifier, qualifier);
3954
3955 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003956 if (member < 0)
3957 continue;
3958
3959 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3960 builder.addMemberDecoration(spvType, member,
3961 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3962 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3963 // Add interpolation and auxiliary storage decorations only to
3964 // top-level members of Input and Output storage classes
3965 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3966 type.getQualifier().storage == glslang::EvqVaryingOut) {
3967 if (type.getBasicType() == glslang::EbtBlock ||
3968 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3969 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3970 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003971#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003972 addMeshNVDecoration(spvType, member, memberQualifier);
3973#endif
John Kessenich6090df02016-06-30 21:18:02 -06003974 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003975 }
3976 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003977
John Kessenichb9197c82019-08-11 07:41:45 -06003978#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003979 if (type.getBasicType() == glslang::EbtBlock &&
3980 qualifier.storage == glslang::EvqBuffer) {
3981 // Add memory decorations only to top-level members of shader storage block
3982 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003983 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003984 for (unsigned int i = 0; i < memory.size(); ++i)
3985 builder.addMemberDecoration(spvType, member, memory[i]);
3986 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003987
John Kessenichb9197c82019-08-11 07:41:45 -06003988#endif
John Kessenich6090df02016-06-30 21:18:02 -06003989
John Kessenich5d610ee2018-03-07 18:05:55 -07003990 // Location assignment was already completed correctly by the front end,
3991 // just track whether a member needs to be decorated.
3992 // Ignore member locations if the container is an array, as that's
3993 // ill-specified and decisions have been made to not allow this.
3994 if (! type.isArray() && memberQualifier.hasLocation())
3995 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003996
John Kessenich5d610ee2018-03-07 18:05:55 -07003997 if (qualifier.hasLocation()) // track for upcoming inheritance
3998 locationOffset += glslangIntermediate->computeTypeLocationSize(
3999 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004000
John Kessenich5d610ee2018-03-07 18:05:55 -07004001 // component, XFB, others
4002 if (glslangMember.getQualifier().hasComponent())
4003 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4004 glslangMember.getQualifier().layoutComponent);
4005 if (glslangMember.getQualifier().hasXfbOffset())
4006 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4007 glslangMember.getQualifier().layoutXfbOffset);
4008 else if (explicitLayout != glslang::ElpNone) {
4009 // figure out what to do with offset, which is accumulating
4010 int nextOffset;
4011 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4012 if (offset >= 0)
4013 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4014 offset = nextOffset;
4015 }
John Kessenich6090df02016-06-30 21:18:02 -06004016
John Kessenich5d610ee2018-03-07 18:05:55 -07004017 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4018 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4019 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004020
John Kessenich5d610ee2018-03-07 18:05:55 -07004021 // built-in variable decorations
4022 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4023 if (builtIn != spv::BuiltInMax)
4024 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004025
John Kessenichb9197c82019-08-11 07:41:45 -06004026#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004027 // nonuniform
4028 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4029
John Kessenichead86222018-03-28 18:01:20 -06004030 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4031 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4032 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4033 memberQualifier.semanticName);
4034 }
4035
John Kessenich5d610ee2018-03-07 18:05:55 -07004036 if (builtIn == spv::BuiltInLayer) {
4037 // SPV_NV_viewport_array2 extension
4038 if (glslangMember.getQualifier().layoutViewportRelative){
4039 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4040 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4041 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004042 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004043 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4044 builder.addMemberDecoration(spvType, member,
4045 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4046 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4047 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4048 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004049 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004050 }
4051 if (glslangMember.getQualifier().layoutPassthrough) {
4052 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4053 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4054 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4055 }
chaoc771d89f2017-01-13 01:10:53 -08004056#endif
John Kessenich6090df02016-06-30 21:18:02 -06004057 }
4058
4059 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004060 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4061 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004062}
4063
John Kessenich6c292d32016-02-15 20:58:50 -07004064// Turn the expression forming the array size into an id.
4065// This is not quite trivial, because of specialization constants.
4066// Sometimes, a raw constant is turned into an Id, and sometimes
4067// a specialization constant expression is.
4068spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4069{
4070 // First, see if this is sized with a node, meaning a specialization constant:
4071 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4072 if (specNode != nullptr) {
4073 builder.clearAccessChain();
4074 specNode->traverse(this);
4075 return accessChainLoad(specNode->getAsTyped()->getType());
4076 }
qining25262b32016-05-06 17:25:16 -04004077
John Kessenich6c292d32016-02-15 20:58:50 -07004078 // Otherwise, need a compile-time (front end) size, get it:
4079 int size = arraySizes.getDimSize(dim);
4080 assert(size > 0);
4081 return builder.makeUintConstant(size);
4082}
4083
John Kessenich103bef92016-02-08 21:38:15 -07004084// Wrap the builder's accessChainLoad to:
4085// - localize handling of RelaxedPrecision
4086// - use the SPIR-V inferred type instead of another conversion of the glslang type
4087// (avoids unnecessary work and possible type punning for structures)
4088// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004089spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4090{
John Kessenich103bef92016-02-08 21:38:15 -07004091 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004092
4093 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4094 coherentFlags |= TranslateCoherent(type);
4095
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004096 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004097 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004098
John Kessenich5611c6d2018-04-05 11:25:02 -06004099 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004100 TranslateNonUniformDecoration(type.getQualifier()),
4101 nominalTypeId,
4102 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4103 TranslateMemoryScope(coherentFlags),
4104 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004105
4106 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004107 if (type.getBasicType() == glslang::EbtBool) {
4108 if (builder.isScalarType(nominalTypeId)) {
4109 // Conversion for bool
4110 spv::Id boolType = builder.makeBoolType();
4111 if (nominalTypeId != boolType)
4112 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4113 } else if (builder.isVectorType(nominalTypeId)) {
4114 // Conversion for bvec
4115 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4116 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4117 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004118 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4119 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004120 }
4121 }
John Kessenich103bef92016-02-08 21:38:15 -07004122
4123 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004124}
4125
Rex Xu27253232016-02-23 17:51:09 +08004126// Wrap the builder's accessChainStore to:
4127// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004128//
4129// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004130void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4131{
4132 // Need to convert to abstract types when necessary
4133 if (type.getBasicType() == glslang::EbtBool) {
4134 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4135
4136 if (builder.isScalarType(nominalTypeId)) {
4137 // Conversion for bool
4138 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004139 if (nominalTypeId != boolType) {
4140 // keep these outside arguments, for determinant order-of-evaluation
4141 spv::Id one = builder.makeUintConstant(1);
4142 spv::Id zero = builder.makeUintConstant(0);
4143 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4144 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004145 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004146 } else if (builder.isVectorType(nominalTypeId)) {
4147 // Conversion for bvec
4148 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4149 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004150 if (nominalTypeId != bvecType) {
4151 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004152 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4153 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4154 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004155 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004156 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4157 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004158 }
4159 }
4160
Jeff Bolz36831c92018-09-05 10:11:41 -05004161 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4162 coherentFlags |= TranslateCoherent(type);
4163
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004164 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004165 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004166
Jeff Bolz36831c92018-09-05 10:11:41 -05004167 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004168 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4169 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004170 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004171}
4172
John Kessenich4bf71552016-09-02 11:20:21 -06004173// For storing when types match at the glslang level, but not might match at the
4174// SPIR-V level.
4175//
4176// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004177// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004178// as in a member-decorated way.
4179//
4180// NOTE: This function can handle any store request; if it's not special it
4181// simplifies to a simple OpStore.
4182//
4183// Implicitly uses the existing builder.accessChain as the storage target.
4184void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4185{
John Kessenichb3e24e42016-09-11 12:33:43 -06004186 // we only do the complex path here if it's an aggregate
4187 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004188 accessChainStore(type, rValue);
4189 return;
4190 }
4191
John Kessenichb3e24e42016-09-11 12:33:43 -06004192 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004193 spv::Id rType = builder.getTypeId(rValue);
4194 spv::Id lValue = builder.accessChainGetLValue();
4195 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4196 if (lType == rType) {
4197 accessChainStore(type, rValue);
4198 return;
4199 }
4200
John Kessenichb3e24e42016-09-11 12:33:43 -06004201 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004202 // where the two types were the same type in GLSL. This requires member
4203 // by member copy, recursively.
4204
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004205 // SPIR-V 1.4 added an instruction to do help do this.
4206 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4207 // However, bool in uniform space is changed to int, so
4208 // OpCopyLogical does not work for that.
4209 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4210 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4211 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4212 if (lBool == rBool) {
4213 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4214 accessChainStore(type, logicalCopy);
4215 return;
4216 }
4217 }
4218
John Kessenichb3e24e42016-09-11 12:33:43 -06004219 // If an array, copy element by element.
4220 if (type.isArray()) {
4221 glslang::TType glslangElementType(type, 0);
4222 spv::Id elementRType = builder.getContainedTypeId(rType);
4223 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4224 // get the source member
4225 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004226
John Kessenichb3e24e42016-09-11 12:33:43 -06004227 // set up the target storage
4228 builder.clearAccessChain();
4229 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004230 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4231 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004232
John Kessenichb3e24e42016-09-11 12:33:43 -06004233 // store the member
4234 multiTypeStore(glslangElementType, elementRValue);
4235 }
4236 } else {
4237 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004238
John Kessenichb3e24e42016-09-11 12:33:43 -06004239 // loop over structure members
4240 const glslang::TTypeList& members = *type.getStruct();
4241 for (int m = 0; m < (int)members.size(); ++m) {
4242 const glslang::TType& glslangMemberType = *members[m].type;
4243
4244 // get the source member
4245 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4246 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4247
4248 // set up the target storage
4249 builder.clearAccessChain();
4250 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004251 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4252 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004253
4254 // store the member
4255 multiTypeStore(glslangMemberType, memberRValue);
4256 }
John Kessenich4bf71552016-09-02 11:20:21 -06004257 }
4258}
4259
John Kessenichf85e8062015-12-19 13:57:10 -07004260// Decide whether or not this type should be
4261// decorated with offsets and strides, and if so
4262// whether std140 or std430 rules should be applied.
4263glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004264{
John Kessenichf85e8062015-12-19 13:57:10 -07004265 // has to be a block
4266 if (type.getBasicType() != glslang::EbtBlock)
4267 return glslang::ElpNone;
4268
Chao Chen3c366992018-09-19 11:41:59 -07004269 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004270 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004271 type.getQualifier().storage != glslang::EvqBuffer &&
4272 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004273 return glslang::ElpNone;
4274
4275 // return the layout to use
4276 switch (type.getQualifier().layoutPacking) {
4277 case glslang::ElpStd140:
4278 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004279 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004280 return type.getQualifier().layoutPacking;
4281 default:
4282 return glslang::ElpNone;
4283 }
John Kessenich31ed4832015-09-09 17:51:38 -06004284}
4285
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004286// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004287int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4288 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004289{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004290 int size;
John Kessenich49987892015-12-29 17:11:44 -07004291 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004292 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4293 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004294
4295 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004296}
4297
John Kessenich49987892015-12-29 17:11:44 -07004298// 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 -07004299// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004300int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4301 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004302{
John Kessenich49987892015-12-29 17:11:44 -07004303 glslang::TType elementType;
4304 elementType.shallowCopy(matrixType);
4305 elementType.clearArraySizes();
4306
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004307 int size;
John Kessenich49987892015-12-29 17:11:44 -07004308 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004309 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4310 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004311
4312 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004313}
4314
John Kessenich5e4b1242015-08-06 22:53:06 -06004315// Given a member type of a struct, realign the current offset for it, and compute
4316// the next (not yet aligned) offset for the next member, which will get aligned
4317// on the next call.
4318// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4319// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4320// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004321void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4322 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004323{
4324 // this will get a positive value when deemed necessary
4325 nextOffset = -1;
4326
John Kessenich5e4b1242015-08-06 22:53:06 -06004327 // override anything in currentOffset with user-set offset
4328 if (memberType.getQualifier().hasOffset())
4329 currentOffset = memberType.getQualifier().layoutOffset;
4330
4331 // It could be that current linker usage in glslang updated all the layoutOffset,
4332 // in which case the following code does not matter. But, that's not quite right
4333 // once cross-compilation unit GLSL validation is done, as the original user
4334 // settings are needed in layoutOffset, and then the following will come into play.
4335
John Kessenichf85e8062015-12-19 13:57:10 -07004336 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004337 if (! memberType.getQualifier().hasOffset())
4338 currentOffset = -1;
4339
4340 return;
4341 }
4342
John Kessenichf85e8062015-12-19 13:57:10 -07004343 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004344 if (currentOffset < 0)
4345 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004346
John Kessenich5e4b1242015-08-06 22:53:06 -06004347 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4348 // but possibly not yet correctly aligned.
4349
4350 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004351 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004352 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4353 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004354
4355 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004356 // TODO: make this consistent in early phases of code:
4357 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4358 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4359 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004360 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004361 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004362 int dummySize;
4363 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4364 if (componentAlignment <= 4)
4365 memberAlignment = componentAlignment;
4366 }
4367
4368 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004369 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004370
4371 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004372 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4373 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004374 glslang::RoundToPow2(currentOffset, 16);
4375
John Kessenich5e4b1242015-08-06 22:53:06 -06004376 nextOffset = currentOffset + memberSize;
4377}
4378
David Netoa901ffe2016-06-08 14:11:40 +01004379void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004380{
David Netoa901ffe2016-06-08 14:11:40 +01004381 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4382 switch (glslangBuiltIn)
4383 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004384 case glslang::EbvPointSize:
4385#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004386 case glslang::EbvClipDistance:
4387 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004388 case glslang::EbvViewportMaskNV:
4389 case glslang::EbvSecondaryPositionNV:
4390 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004391 case glslang::EbvPositionPerViewNV:
4392 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004393 case glslang::EbvTaskCountNV:
4394 case glslang::EbvPrimitiveCountNV:
4395 case glslang::EbvPrimitiveIndicesNV:
4396 case glslang::EbvClipDistancePerViewNV:
4397 case glslang::EbvCullDistancePerViewNV:
4398 case glslang::EbvLayerPerViewNV:
4399 case glslang::EbvMeshViewCountNV:
4400 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004401#endif
David Netoa901ffe2016-06-08 14:11:40 +01004402 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4403 // Alternately, we could just call this for any glslang built-in, since the
4404 // capability already guards against duplicates.
4405 TranslateBuiltInDecoration(glslangBuiltIn, false);
4406 break;
4407 default:
4408 // Capabilities were already generated when the struct was declared.
4409 break;
4410 }
John Kessenichebb50532016-05-16 19:22:05 -06004411}
4412
John Kessenich6fccb3c2016-09-19 16:01:41 -06004413bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004414{
John Kessenicheee9d532016-09-19 18:09:30 -06004415 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004416}
4417
John Kessenichd41993d2017-09-10 15:21:05 -06004418// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004419// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4420// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004421bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004422{
John Kessenich6a14f782017-12-04 02:48:10 -07004423 assert(qualifier == glslang::EvqIn ||
4424 qualifier == glslang::EvqOut ||
4425 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004426 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004427 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004428 return qualifier != glslang::EvqConstReadOnly &&
4429 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004430}
4431
4432// Is parameter pass-by-original?
4433bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4434 bool implicitThisParam)
4435{
4436 if (implicitThisParam) // implicit this
4437 return true;
4438 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004439 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004440 return paramType.containsOpaque() || // sampler, etc.
4441 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4442}
4443
John Kessenich140f3df2015-06-26 16:58:36 -06004444// Make all the functions, skeletally, without actually visiting their bodies.
4445void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4446{
John Kessenich8985fc92020-03-03 10:25:07 -07004447 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4448 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004449 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4450 if (paramPrecision != spv::NoPrecision)
4451 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004452 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004453 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004454 // Original and non-writable params pass the pointer directly and
4455 // use restrict/aliased, others are stored to a pointer in Function
4456 // memory and use RestrictPointer/AliasedPointer.
4457 if (originalParam(type.getQualifier().storage, type, false) ||
4458 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004459 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4460 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004461 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004462 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4463 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004464 }
4465 }
John Kessenichfad62972017-07-18 02:35:46 -06004466 };
4467
John Kessenich140f3df2015-06-26 16:58:36 -06004468 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4469 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004470 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004471 continue;
4472
4473 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004474 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004475 //
qining25262b32016-05-06 17:25:16 -04004476 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004477 // function. What it is an address of varies:
4478 //
John Kessenich4bf71552016-09-02 11:20:21 -06004479 // - "in" parameters not marked as "const" can be written to without modifying the calling
4480 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004481 //
4482 // - "const in" parameters can just be the r-value, as no writes need occur.
4483 //
John Kessenich4bf71552016-09-02 11:20:21 -06004484 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4485 // 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 -06004486
4487 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004488 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004489 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4490
John Kessenich155d3512019-08-08 23:29:20 -06004491#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004492 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4493 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004494#else
4495 bool implicitThis = false;
4496#endif
John Kessenich37789792017-03-21 23:56:40 -06004497
John Kessenichfad62972017-07-18 02:35:46 -06004498 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004499 for (int p = 0; p < (int)parameters.size(); ++p) {
4500 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4501 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004502 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004503 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004504 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004505 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4506 else
John Kessenich4bf71552016-09-02 11:20:21 -06004507 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004508 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004509 paramTypes.push_back(typeId);
4510 }
4511
4512 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004513 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4514 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004515 glslFunction->getName().c_str(), paramTypes,
4516 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004517 if (implicitThis)
4518 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004519
4520 // Track function to emit/call later
4521 functionMap[glslFunction->getName().c_str()] = function;
4522
4523 // Set the parameter id's
4524 for (int p = 0; p < (int)parameters.size(); ++p) {
4525 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4526 // give a name too
4527 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004528
4529 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004530 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004531 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004532 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004533 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004534 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004535 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004536 }
4537 }
4538}
4539
4540// Process all the initializers, while skipping the functions and link objects
4541void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4542{
4543 builder.setBuildPoint(shaderEntry->getLastBlock());
4544 for (int i = 0; i < (int)initializers.size(); ++i) {
4545 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004546 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4547 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004548
4549 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004550 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004551 initializer->traverse(this);
4552 }
4553 }
4554}
4555
4556// Process all the functions, while skipping initializers.
4557void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4558{
4559 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4560 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004561 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004562 node->traverse(this);
4563 }
4564}
4565
4566void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4567{
qining25262b32016-05-06 17:25:16 -04004568 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004569 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004570 currentFunction = functionMap[node->getName().c_str()];
4571 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004572 builder.setBuildPoint(functionBlock);
4573}
4574
John Kessenich8985fc92020-03-03 10:25:07 -07004575void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4576 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004577{
Rex Xufc618912015-09-09 16:42:49 +08004578 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004579
4580 glslang::TSampler sampler = {};
4581 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004582#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004583 bool f16ShadowCompare = false;
4584#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004585 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004586 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4587 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004588#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004589 f16ShadowCompare = sampler.shadow &&
4590 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004591#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004592 }
4593
John Kessenich140f3df2015-06-26 16:58:36 -06004594 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4595 builder.clearAccessChain();
4596 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004597
John Kessenicha28f7a72019-08-06 07:00:58 -06004598#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004599 // Special case l-value operands
4600 bool lvalue = false;
4601 switch (node.getOp()) {
4602 case glslang::EOpImageAtomicAdd:
4603 case glslang::EOpImageAtomicMin:
4604 case glslang::EOpImageAtomicMax:
4605 case glslang::EOpImageAtomicAnd:
4606 case glslang::EOpImageAtomicOr:
4607 case glslang::EOpImageAtomicXor:
4608 case glslang::EOpImageAtomicExchange:
4609 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004610 case glslang::EOpImageAtomicLoad:
4611 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004612 if (i == 0)
4613 lvalue = true;
4614 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004615 case glslang::EOpSparseImageLoad:
4616 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4617 lvalue = true;
4618 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004619 case glslang::EOpSparseTexture:
4620 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4621 lvalue = true;
4622 break;
4623 case glslang::EOpSparseTextureClamp:
4624 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4625 lvalue = true;
4626 break;
4627 case glslang::EOpSparseTextureLod:
4628 case glslang::EOpSparseTextureOffset:
4629 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4630 lvalue = true;
4631 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004632 case glslang::EOpSparseTextureFetch:
4633 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4634 lvalue = true;
4635 break;
4636 case glslang::EOpSparseTextureFetchOffset:
4637 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4638 lvalue = true;
4639 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004640 case glslang::EOpSparseTextureLodOffset:
4641 case glslang::EOpSparseTextureGrad:
4642 case glslang::EOpSparseTextureOffsetClamp:
4643 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4644 lvalue = true;
4645 break;
4646 case glslang::EOpSparseTextureGradOffset:
4647 case glslang::EOpSparseTextureGradClamp:
4648 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4649 lvalue = true;
4650 break;
4651 case glslang::EOpSparseTextureGradOffsetClamp:
4652 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4653 lvalue = true;
4654 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004655 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004656 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4657 lvalue = true;
4658 break;
4659 case glslang::EOpSparseTextureGatherOffset:
4660 case glslang::EOpSparseTextureGatherOffsets:
4661 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4662 lvalue = true;
4663 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004664 case glslang::EOpSparseTextureGatherLod:
4665 if (i == 3)
4666 lvalue = true;
4667 break;
4668 case glslang::EOpSparseTextureGatherLodOffset:
4669 case glslang::EOpSparseTextureGatherLodOffsets:
4670 if (i == 4)
4671 lvalue = true;
4672 break;
Rex Xu129799a2017-07-05 17:23:28 +08004673 case glslang::EOpSparseImageLoadLod:
4674 if (i == 3)
4675 lvalue = true;
4676 break;
Chao Chen3a137962018-09-19 11:41:27 -07004677 case glslang::EOpImageSampleFootprintNV:
4678 if (i == 4)
4679 lvalue = true;
4680 break;
4681 case glslang::EOpImageSampleFootprintClampNV:
4682 case glslang::EOpImageSampleFootprintLodNV:
4683 if (i == 5)
4684 lvalue = true;
4685 break;
4686 case glslang::EOpImageSampleFootprintGradNV:
4687 if (i == 6)
4688 lvalue = true;
4689 break;
4690 case glslang::EOpImageSampleFootprintGradClampNV:
4691 if (i == 7)
4692 lvalue = true;
4693 break;
Rex Xufc618912015-09-09 16:42:49 +08004694 default:
4695 break;
4696 }
4697
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004698 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004699 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004700 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4701 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4702 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004703#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004704 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004705 }
4706}
4707
John Kessenichfc51d282015-08-19 13:34:18 -06004708void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004709{
John Kessenichfc51d282015-08-19 13:34:18 -06004710 builder.clearAccessChain();
4711 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004712 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004713}
John Kessenich140f3df2015-06-26 16:58:36 -06004714
John Kessenichfc51d282015-08-19 13:34:18 -06004715spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4716{
John Kesseniche485c7a2017-05-31 18:50:53 -06004717 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004718 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004719
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004720 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004721
John Kessenichfc51d282015-08-19 13:34:18 -06004722 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004723
John Kessenichf43c7392019-03-31 10:51:57 -06004724 const glslang::TType &imageType = node->getAsAggregate()
4725 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4726 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004727 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004728#ifdef GLSLANG_WEB
4729 const bool f16ShadowCompare = false;
4730#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004731 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004732 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4733 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004734#endif
4735
John Kessenichf43c7392019-03-31 10:51:57 -06004736 const auto signExtensionMask = [&]() {
4737 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4738 if (sampler.type == glslang::EbtUint)
4739 return spv::ImageOperandsZeroExtendMask;
4740 else if (sampler.type == glslang::EbtInt)
4741 return spv::ImageOperandsSignExtendMask;
4742 }
4743 return spv::ImageOperandsMaskNone;
4744 };
4745
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004746 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4747
John Kessenichfc51d282015-08-19 13:34:18 -06004748 std::vector<spv::Id> arguments;
4749 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004750 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004751 else
4752 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004753 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004754
4755 spv::Builder::TextureParameters params = { };
4756 params.sampler = arguments[0];
4757
Rex Xu04db3f52015-09-16 11:44:02 +08004758 glslang::TCrackedTextureOp cracked;
4759 node->crackTexture(sampler, cracked);
4760
amhagan05506bb2017-06-13 16:53:02 -04004761 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004762
John Kessenichfc51d282015-08-19 13:34:18 -06004763 // Check for queries
4764 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004765 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4766 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004767 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004768
John Kessenichfc51d282015-08-19 13:34:18 -06004769 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
5022 // Extract the image if necessary
5023 if (builder.isSampledImage(params.sampler))
5024 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5025
5026 operands.push_back(params.sampler);
5027 ++opIt;
5028
5029 if (sampler.isSubpass()) {
5030 // add on the (0,0) coordinate
5031 spv::Id zero = builder.makeIntConstant(0);
5032 std::vector<spv::Id> comps;
5033 comps.push_back(zero);
5034 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005035 operands.push_back(builder.makeCompositeConstant(
5036 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005037 }
5038
5039 for (; opIt != arguments.end(); ++opIt)
5040 operands.push_back(*opIt);
5041
5042 spv::Op fragMaskOp = spv::OpNop;
5043 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5044 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5045 else if (node->getOp() == glslang::EOpFragmentFetch)
5046 fragMaskOp = spv::OpFragmentFetchAMD;
5047
5048 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5049 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5050 return builder.createOp(fragMaskOp, resultType(), operands);
5051 }
5052#endif
5053
Rex Xufc618912015-09-09 16:42:49 +08005054 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005055 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005056 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005057 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005058
John Kessenichfc51d282015-08-19 13:34:18 -06005059 // check for bias argument
5060 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005061 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005062 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005063 if (cracked.gather)
5064 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005065
5066 if (f16ShadowCompare)
5067 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005068 if (cracked.offset)
5069 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005070 else if (cracked.offsets)
5071 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005072 if (cracked.grad)
5073 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005074 if (cracked.lodClamp)
5075 ++nonBiasArgCount;
5076 if (sparse)
5077 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005078 if (imageFootprint)
5079 //Following three extra arguments
5080 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5081 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005082 if ((int)arguments.size() > nonBiasArgCount)
5083 bias = true;
5084 }
5085
John Kessenicha5c33d62016-06-02 23:45:21 -06005086 // See if the sampler param should really be just the SPV image part
5087 if (cracked.fetch) {
5088 // a fetch needs to have the image extracted first
5089 if (builder.isSampledImage(params.sampler))
5090 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5091 }
5092
John Kessenicha28f7a72019-08-06 07:00:58 -06005093#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005094 if (cracked.gather) {
5095 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5096 if (bias || cracked.lod ||
5097 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5098 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005099 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005100 }
5101 }
5102#endif
5103
John Kessenichfc51d282015-08-19 13:34:18 -06005104 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005105
John Kessenichfc51d282015-08-19 13:34:18 -06005106 params.coords = arguments[1];
5107 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005108 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005109
5110 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005111 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005112 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005113 ++extraArgs;
5114 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005115 params.Dref = arguments[2];
5116 ++extraArgs;
5117 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005118 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005119 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005120 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005121 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005122 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005123 dRefComp = builder.getNumComponents(params.coords) - 1;
5124 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005125 params.Dref = builder.createCompositeExtract(params.coords,
5126 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005127 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005128
5129 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005130 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005131 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005132 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005133 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5134 !(glslangIntermediate->getStage() == EShLangCompute &&
5135 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005136 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5137 noImplicitLod = true;
5138 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005139
5140 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005141 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005142 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005143 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005144 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005145
5146 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005147 if (cracked.grad) {
5148 params.gradX = arguments[2 + extraArgs];
5149 params.gradY = arguments[3 + extraArgs];
5150 extraArgs += 2;
5151 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005152
5153 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005154 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005155 params.offset = arguments[2 + extraArgs];
5156 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005157 } else if (cracked.offsets) {
5158 params.offsets = arguments[2 + extraArgs];
5159 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005160 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005161
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005162#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005163 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005164 if (cracked.lodClamp) {
5165 params.lodClamp = arguments[2 + extraArgs];
5166 ++extraArgs;
5167 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005168 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005169 if (sparse) {
5170 params.texelOut = arguments[2 + extraArgs];
5171 ++extraArgs;
5172 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005173 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005174 if (cracked.gather && ! sampler.shadow) {
5175 // default component is 0, if missing, otherwise an argument
5176 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005177 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005178 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005179 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005180 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005181 }
Chao Chen3a137962018-09-19 11:41:27 -07005182 spv::Id resultStruct = spv::NoResult;
5183 if (imageFootprint) {
5184 //Following three extra arguments
5185 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5186 params.granularity = arguments[2 + extraArgs];
5187 params.coarse = arguments[3 + extraArgs];
5188 resultStruct = arguments[4 + extraArgs];
5189 extraArgs += 3;
5190 }
5191#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005192 // bias
5193 if (bias) {
5194 params.bias = arguments[2 + extraArgs];
5195 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005196 }
John Kessenichfc51d282015-08-19 13:34:18 -06005197
John Kessenicha28f7a72019-08-06 07:00:58 -06005198#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005199 if (imageFootprint) {
5200 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5201 builder.addCapability(spv::CapabilityImageFootprintNV);
5202
5203
5204 //resultStructType(OpenGL type) contains 5 elements:
5205 //struct gl_TextureFootprint2DNV {
5206 // uvec2 anchor;
5207 // uvec2 offset;
5208 // uvec2 mask;
5209 // uint lod;
5210 // uint granularity;
5211 //};
5212 //or
5213 //struct gl_TextureFootprint3DNV {
5214 // uvec3 anchor;
5215 // uvec3 offset;
5216 // uvec2 mask;
5217 // uint lod;
5218 // uint granularity;
5219 //};
5220 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5221 assert(builder.isStructType(resultStructType));
5222
5223 //resType (SPIR-V type) contains 6 elements:
5224 //Member 0 must be a Boolean type scalar(LOD),
5225 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5226 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5227 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5228 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5229 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5230 std::vector<spv::Id> members;
5231 members.push_back(resultType());
5232 for (int i = 0; i < 5; i++) {
5233 members.push_back(builder.getContainedTypeId(resultStructType, i));
5234 }
5235 spv::Id resType = builder.makeStructType(members, "ResType");
5236
5237 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005238 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5239 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005240
5241 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5242 for (int i = 0; i < 5; i++) {
5243 builder.clearAccessChain();
5244 builder.setAccessChainLValue(resultStruct);
5245
5246 //Accessing to a struct we created, no coherent flag is set
5247 spv::Builder::AccessChain::CoherentFlags flags;
5248 flags.clear();
5249
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005250 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005251 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5252 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005253 }
5254 return builder.createCompositeExtract(res, resultType(), 0);
5255 }
5256#endif
5257
John Kessenich65336482016-06-16 14:06:26 -06005258 // projective component (might not to move)
5259 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5260 // are divided by the last component of P."
5261 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5262 // unused components will appear after all used components."
5263 if (cracked.proj) {
5264 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5265 int projTargetComp;
5266 switch (sampler.dim) {
5267 case glslang::Esd1D: projTargetComp = 1; break;
5268 case glslang::Esd2D: projTargetComp = 2; break;
5269 case glslang::EsdRect: projTargetComp = 2; break;
5270 default: projTargetComp = projSourceComp; break;
5271 }
5272 // copy the projective coordinate if we have to
5273 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005274 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005275 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005276 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005277 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005278 }
5279 }
5280
John Kessenichf8d1d742019-10-21 06:55:11 -06005281#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005282 // nonprivate
5283 if (imageType.getQualifier().nonprivate) {
5284 params.nonprivate = true;
5285 }
5286
5287 // volatile
5288 if (imageType.getQualifier().volatil) {
5289 params.volatil = true;
5290 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005291#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005292
St0fFa1184dd2018-04-09 21:08:14 +02005293 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005294 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5295 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005296 );
LoopDawg4425f242018-02-18 11:40:01 -07005297
5298 if (components != node->getType().getVectorSize())
5299 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5300
5301 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005302}
5303
5304spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5305{
5306 // Grab the function's pointer from the previously created function
5307 spv::Function* function = functionMap[node->getName().c_str()];
5308 if (! function)
5309 return 0;
5310
5311 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5312 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5313
5314 // See comments in makeFunctions() for details about the semantics for parameter passing.
5315 //
5316 // These imply we need a four step process:
5317 // 1. Evaluate the arguments
5318 // 2. Allocate and make copies of in, out, and inout arguments
5319 // 3. Make the call
5320 // 4. Copy back the results
5321
John Kessenichd3ed90b2018-05-04 11:43:03 -06005322 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005323 std::vector<spv::Builder::AccessChain> lValues;
5324 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005325 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005326 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005327 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005328 // build l-value
5329 builder.clearAccessChain();
5330 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005331 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005332 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005333 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005334 // save l-value
5335 lValues.push_back(builder.getAccessChain());
5336 } else {
5337 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005338 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005339 }
5340 }
5341
5342 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5343 // copy the original into that space.
5344 //
5345 // Also, build up the list of actual arguments to pass in for the call
5346 int lValueCount = 0;
5347 int rValueCount = 0;
5348 std::vector<spv::Id> spvArgs;
5349 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5350 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005351 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005352 builder.setAccessChain(lValues[lValueCount]);
5353 arg = builder.accessChainGetLValue();
5354 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005355 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005356 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005357 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005358 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005359 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5360 // need to copy the input into output space
5361 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005362 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005363 builder.clearAccessChain();
5364 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005365 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005366 }
5367 ++lValueCount;
5368 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005369 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005370 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005371 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005372 {
John Kessenich435dd802020-06-30 01:27:08 -06005373 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005374 builder.clearAccessChain();
5375 builder.setAccessChainLValue(argCopy);
5376 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005377 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005378 } else
5379 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005380 ++rValueCount;
5381 }
5382 spvArgs.push_back(arg);
5383 }
5384
5385 // 3. Make the call.
5386 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005387 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005388
5389 // 4. Copy back out an "out" arguments.
5390 lValueCount = 0;
5391 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005392 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005393 ++lValueCount;
5394 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005395 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005396 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005397 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005398 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005399 }
5400 ++lValueCount;
5401 }
5402 }
5403
5404 return result;
5405}
5406
5407// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005408spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005409 spv::Id typeId, spv::Id left, spv::Id right,
5410 glslang::TBasicType typeProxy, bool reduceComparison)
5411{
John Kessenich66011cb2018-03-06 16:12:04 -07005412 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5413 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005414 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005415
5416 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005417 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005418 bool comparison = false;
5419
5420 switch (op) {
5421 case glslang::EOpAdd:
5422 case glslang::EOpAddAssign:
5423 if (isFloat)
5424 binOp = spv::OpFAdd;
5425 else
5426 binOp = spv::OpIAdd;
5427 break;
5428 case glslang::EOpSub:
5429 case glslang::EOpSubAssign:
5430 if (isFloat)
5431 binOp = spv::OpFSub;
5432 else
5433 binOp = spv::OpISub;
5434 break;
5435 case glslang::EOpMul:
5436 case glslang::EOpMulAssign:
5437 if (isFloat)
5438 binOp = spv::OpFMul;
5439 else
5440 binOp = spv::OpIMul;
5441 break;
5442 case glslang::EOpVectorTimesScalar:
5443 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005444 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005445 if (builder.isVector(right))
5446 std::swap(left, right);
5447 assert(builder.isScalar(right));
5448 needMatchingVectors = false;
5449 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005450 } else if (isFloat)
5451 binOp = spv::OpFMul;
5452 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005453 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005454 break;
5455 case glslang::EOpVectorTimesMatrix:
5456 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005457 binOp = spv::OpVectorTimesMatrix;
5458 break;
5459 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005460 binOp = spv::OpMatrixTimesVector;
5461 break;
5462 case glslang::EOpMatrixTimesScalar:
5463 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005464 binOp = spv::OpMatrixTimesScalar;
5465 break;
5466 case glslang::EOpMatrixTimesMatrix:
5467 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005468 binOp = spv::OpMatrixTimesMatrix;
5469 break;
5470 case glslang::EOpOuterProduct:
5471 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005472 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005473 break;
5474
5475 case glslang::EOpDiv:
5476 case glslang::EOpDivAssign:
5477 if (isFloat)
5478 binOp = spv::OpFDiv;
5479 else if (isUnsigned)
5480 binOp = spv::OpUDiv;
5481 else
5482 binOp = spv::OpSDiv;
5483 break;
5484 case glslang::EOpMod:
5485 case glslang::EOpModAssign:
5486 if (isFloat)
5487 binOp = spv::OpFMod;
5488 else if (isUnsigned)
5489 binOp = spv::OpUMod;
5490 else
5491 binOp = spv::OpSMod;
5492 break;
5493 case glslang::EOpRightShift:
5494 case glslang::EOpRightShiftAssign:
5495 if (isUnsigned)
5496 binOp = spv::OpShiftRightLogical;
5497 else
5498 binOp = spv::OpShiftRightArithmetic;
5499 break;
5500 case glslang::EOpLeftShift:
5501 case glslang::EOpLeftShiftAssign:
5502 binOp = spv::OpShiftLeftLogical;
5503 break;
5504 case glslang::EOpAnd:
5505 case glslang::EOpAndAssign:
5506 binOp = spv::OpBitwiseAnd;
5507 break;
5508 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005509 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005510 binOp = spv::OpLogicalAnd;
5511 break;
5512 case glslang::EOpInclusiveOr:
5513 case glslang::EOpInclusiveOrAssign:
5514 binOp = spv::OpBitwiseOr;
5515 break;
5516 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005517 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005518 binOp = spv::OpLogicalOr;
5519 break;
5520 case glslang::EOpExclusiveOr:
5521 case glslang::EOpExclusiveOrAssign:
5522 binOp = spv::OpBitwiseXor;
5523 break;
5524 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005525 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005526 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005527 break;
5528
Ian Romanickb3bd4022019-01-21 08:57:25 -08005529 case glslang::EOpAbsDifference:
5530 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5531 break;
5532
5533 case glslang::EOpAddSaturate:
5534 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5535 break;
5536
5537 case glslang::EOpSubSaturate:
5538 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5539 break;
5540
5541 case glslang::EOpAverage:
5542 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5543 break;
5544
5545 case glslang::EOpAverageRounded:
5546 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5547 break;
5548
5549 case glslang::EOpMul32x16:
5550 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5551 break;
5552
John Kessenich140f3df2015-06-26 16:58:36 -06005553 case glslang::EOpLessThan:
5554 case glslang::EOpGreaterThan:
5555 case glslang::EOpLessThanEqual:
5556 case glslang::EOpGreaterThanEqual:
5557 case glslang::EOpEqual:
5558 case glslang::EOpNotEqual:
5559 case glslang::EOpVectorEqual:
5560 case glslang::EOpVectorNotEqual:
5561 comparison = true;
5562 break;
5563 default:
5564 break;
5565 }
5566
John Kessenich7c1aa102015-10-15 13:29:11 -06005567 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005568 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005569 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005570 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5571 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005572 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005573
5574 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005575 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005576 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005577
qining25262b32016-05-06 17:25:16 -04005578 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005579 decorations.addNoContraction(builder, result);
5580 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005581 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005582 }
5583
5584 if (! comparison)
5585 return 0;
5586
John Kessenich7c1aa102015-10-15 13:29:11 -06005587 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005588
John Kessenich4583b612016-08-07 19:14:22 -06005589 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005590 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5591 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005592 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005593 return result;
5594 }
John Kessenich140f3df2015-06-26 16:58:36 -06005595
5596 switch (op) {
5597 case glslang::EOpLessThan:
5598 if (isFloat)
5599 binOp = spv::OpFOrdLessThan;
5600 else if (isUnsigned)
5601 binOp = spv::OpULessThan;
5602 else
5603 binOp = spv::OpSLessThan;
5604 break;
5605 case glslang::EOpGreaterThan:
5606 if (isFloat)
5607 binOp = spv::OpFOrdGreaterThan;
5608 else if (isUnsigned)
5609 binOp = spv::OpUGreaterThan;
5610 else
5611 binOp = spv::OpSGreaterThan;
5612 break;
5613 case glslang::EOpLessThanEqual:
5614 if (isFloat)
5615 binOp = spv::OpFOrdLessThanEqual;
5616 else if (isUnsigned)
5617 binOp = spv::OpULessThanEqual;
5618 else
5619 binOp = spv::OpSLessThanEqual;
5620 break;
5621 case glslang::EOpGreaterThanEqual:
5622 if (isFloat)
5623 binOp = spv::OpFOrdGreaterThanEqual;
5624 else if (isUnsigned)
5625 binOp = spv::OpUGreaterThanEqual;
5626 else
5627 binOp = spv::OpSGreaterThanEqual;
5628 break;
5629 case glslang::EOpEqual:
5630 case glslang::EOpVectorEqual:
5631 if (isFloat)
5632 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005633 else if (isBool)
5634 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005635 else
5636 binOp = spv::OpIEqual;
5637 break;
5638 case glslang::EOpNotEqual:
5639 case glslang::EOpVectorNotEqual:
5640 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005641 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005642 else if (isBool)
5643 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005644 else
5645 binOp = spv::OpINotEqual;
5646 break;
5647 default:
5648 break;
5649 }
5650
qining25262b32016-05-06 17:25:16 -04005651 if (binOp != spv::OpNop) {
5652 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005653 decorations.addNoContraction(builder, result);
5654 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005655 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005656 }
John Kessenich140f3df2015-06-26 16:58:36 -06005657
5658 return 0;
5659}
5660
John Kessenich04bb8a02015-12-12 12:28:14 -07005661//
5662// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5663// These can be any of:
5664//
5665// matrix * scalar
5666// scalar * matrix
5667// matrix * matrix linear algebraic
5668// matrix * vector
5669// vector * matrix
5670// matrix * matrix componentwise
5671// matrix op matrix op in {+, -, /}
5672// matrix op scalar op in {+, -, /}
5673// scalar op matrix op in {+, -, /}
5674//
John Kessenichead86222018-03-28 18:01:20 -06005675spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5676 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005677{
5678 bool firstClass = true;
5679
5680 // First, handle first-class matrix operations (* and matrix/scalar)
5681 switch (op) {
5682 case spv::OpFDiv:
5683 if (builder.isMatrix(left) && builder.isScalar(right)) {
5684 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005685 spv::Id resultType = builder.getTypeId(right);
5686 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005687 op = spv::OpMatrixTimesScalar;
5688 } else
5689 firstClass = false;
5690 break;
5691 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005692 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005693 std::swap(left, right);
5694 assert(builder.isScalar(right));
5695 break;
5696 case spv::OpVectorTimesMatrix:
5697 assert(builder.isVector(left));
5698 assert(builder.isMatrix(right));
5699 break;
5700 case spv::OpMatrixTimesVector:
5701 assert(builder.isMatrix(left));
5702 assert(builder.isVector(right));
5703 break;
5704 case spv::OpMatrixTimesMatrix:
5705 assert(builder.isMatrix(left));
5706 assert(builder.isMatrix(right));
5707 break;
5708 default:
5709 firstClass = false;
5710 break;
5711 }
5712
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005713 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5714 firstClass = true;
5715
qining25262b32016-05-06 17:25:16 -04005716 if (firstClass) {
5717 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005718 decorations.addNoContraction(builder, result);
5719 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005720 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005721 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005722
LoopDawg592860c2016-06-09 08:57:35 -06005723 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005724 // The result type of all of them is the same type as the (a) matrix operand.
5725 // The algorithm is to:
5726 // - break the matrix(es) into vectors
5727 // - smear any scalar to a vector
5728 // - do vector operations
5729 // - make a matrix out the vector results
5730 switch (op) {
5731 case spv::OpFAdd:
5732 case spv::OpFSub:
5733 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005734 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005735 case spv::OpFMul:
5736 {
5737 // one time set up...
5738 bool leftMat = builder.isMatrix(left);
5739 bool rightMat = builder.isMatrix(right);
5740 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5741 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5742 spv::Id scalarType = builder.getScalarTypeId(typeId);
5743 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5744 std::vector<spv::Id> results;
5745 spv::Id smearVec = spv::NoResult;
5746 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005747 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005748 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005749 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005750
5751 // do each vector op
5752 for (unsigned int c = 0; c < numCols; ++c) {
5753 std::vector<unsigned int> indexes;
5754 indexes.push_back(c);
5755 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5756 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005757 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005758 decorations.addNoContraction(builder, result);
5759 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005760 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005761 }
5762
5763 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005764 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005765 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005766 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005767 }
5768 default:
5769 assert(0);
5770 return spv::NoResult;
5771 }
5772}
5773
John Kessenichead86222018-03-28 18:01:20 -06005774spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005775 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005776{
5777 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005778 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005779 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005780 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5781 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005782
5783 switch (op) {
5784 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005785 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005786 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005787 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005788 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005789 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005790 unaryOp = spv::OpSNegate;
5791 break;
5792
5793 case glslang::EOpLogicalNot:
5794 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005795 unaryOp = spv::OpLogicalNot;
5796 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005797 case glslang::EOpBitwiseNot:
5798 unaryOp = spv::OpNot;
5799 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005800
John Kessenich140f3df2015-06-26 16:58:36 -06005801 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005802 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005803 break;
5804 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005805 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005806 break;
5807 case glslang::EOpTranspose:
5808 unaryOp = spv::OpTranspose;
5809 break;
5810
5811 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005812 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005813 break;
5814 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005815 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005816 break;
5817 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005818 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005821 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005822 break;
5823 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005824 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005825 break;
5826 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005827 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
5829 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005830 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005831 break;
5832 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005833 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005834 break;
5835
5836 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005837 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005838 break;
5839 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005840 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005841 break;
5842 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005843 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005844 break;
5845 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005846 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005847 break;
5848 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005849 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005850 break;
5851 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005852 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005853 break;
5854
5855 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005856 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005857 break;
5858 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005859 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005860 break;
5861
5862 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005863 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005864 break;
5865 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005866 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005867 break;
5868 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005869 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005870 break;
5871 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005872 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005873 break;
5874 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005875 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005876 break;
5877 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005878 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005879 break;
5880
5881 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005882 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005883 break;
5884 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005885 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005886 break;
5887 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005888 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005889 break;
5890 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005891 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005892 break;
5893 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005894 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005895 break;
5896 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005897 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005898 break;
5899
5900 case glslang::EOpIsNan:
5901 unaryOp = spv::OpIsNan;
5902 break;
5903 case glslang::EOpIsInf:
5904 unaryOp = spv::OpIsInf;
5905 break;
LoopDawg592860c2016-06-09 08:57:35 -06005906 case glslang::EOpIsFinite:
5907 unaryOp = spv::OpIsFinite;
5908 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005909
Rex Xucbc426e2015-12-15 16:03:10 +08005910 case glslang::EOpFloatBitsToInt:
5911 case glslang::EOpFloatBitsToUint:
5912 case glslang::EOpIntBitsToFloat:
5913 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005914 case glslang::EOpDoubleBitsToInt64:
5915 case glslang::EOpDoubleBitsToUint64:
5916 case glslang::EOpInt64BitsToDouble:
5917 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005918 case glslang::EOpFloat16BitsToInt16:
5919 case glslang::EOpFloat16BitsToUint16:
5920 case glslang::EOpInt16BitsToFloat16:
5921 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005922 unaryOp = spv::OpBitcast;
5923 break;
5924
John Kessenich140f3df2015-06-26 16:58:36 -06005925 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005926 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005927 break;
5928 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005929 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005930 break;
5931 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005932 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005933 break;
5934 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005935 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005936 break;
5937 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005938 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005939 break;
5940 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005941 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005942 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005943#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005944 case glslang::EOpPackSnorm4x8:
5945 libCall = spv::GLSLstd450PackSnorm4x8;
5946 break;
5947 case glslang::EOpUnpackSnorm4x8:
5948 libCall = spv::GLSLstd450UnpackSnorm4x8;
5949 break;
5950 case glslang::EOpPackUnorm4x8:
5951 libCall = spv::GLSLstd450PackUnorm4x8;
5952 break;
5953 case glslang::EOpUnpackUnorm4x8:
5954 libCall = spv::GLSLstd450UnpackUnorm4x8;
5955 break;
5956 case glslang::EOpPackDouble2x32:
5957 libCall = spv::GLSLstd450PackDouble2x32;
5958 break;
5959 case glslang::EOpUnpackDouble2x32:
5960 libCall = spv::GLSLstd450UnpackDouble2x32;
5961 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005962#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005963
Rex Xu8ff43de2016-04-22 16:51:45 +08005964 case glslang::EOpPackInt2x32:
5965 case glslang::EOpUnpackInt2x32:
5966 case glslang::EOpPackUint2x32:
5967 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005968 case glslang::EOpPack16:
5969 case glslang::EOpPack32:
5970 case glslang::EOpPack64:
5971 case glslang::EOpUnpack32:
5972 case glslang::EOpUnpack16:
5973 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005974 case glslang::EOpPackInt2x16:
5975 case glslang::EOpUnpackInt2x16:
5976 case glslang::EOpPackUint2x16:
5977 case glslang::EOpUnpackUint2x16:
5978 case glslang::EOpPackInt4x16:
5979 case glslang::EOpUnpackInt4x16:
5980 case glslang::EOpPackUint4x16:
5981 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005982 case glslang::EOpPackFloat2x16:
5983 case glslang::EOpUnpackFloat2x16:
5984 unaryOp = spv::OpBitcast;
5985 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005986
John Kessenich140f3df2015-06-26 16:58:36 -06005987 case glslang::EOpDPdx:
5988 unaryOp = spv::OpDPdx;
5989 break;
5990 case glslang::EOpDPdy:
5991 unaryOp = spv::OpDPdy;
5992 break;
5993 case glslang::EOpFwidth:
5994 unaryOp = spv::OpFwidth;
5995 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005996
John Kessenich140f3df2015-06-26 16:58:36 -06005997 case glslang::EOpAny:
5998 unaryOp = spv::OpAny;
5999 break;
6000 case glslang::EOpAll:
6001 unaryOp = spv::OpAll;
6002 break;
6003
6004 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006005 if (isFloat)
6006 libCall = spv::GLSLstd450FAbs;
6007 else
6008 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006009 break;
6010 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006011 if (isFloat)
6012 libCall = spv::GLSLstd450FSign;
6013 else
6014 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006015 break;
6016
John Kessenicha28f7a72019-08-06 07:00:58 -06006017#ifndef GLSLANG_WEB
6018 case glslang::EOpDPdxFine:
6019 unaryOp = spv::OpDPdxFine;
6020 break;
6021 case glslang::EOpDPdyFine:
6022 unaryOp = spv::OpDPdyFine;
6023 break;
6024 case glslang::EOpFwidthFine:
6025 unaryOp = spv::OpFwidthFine;
6026 break;
6027 case glslang::EOpDPdxCoarse:
6028 unaryOp = spv::OpDPdxCoarse;
6029 break;
6030 case glslang::EOpDPdyCoarse:
6031 unaryOp = spv::OpDPdyCoarse;
6032 break;
6033 case glslang::EOpFwidthCoarse:
6034 unaryOp = spv::OpFwidthCoarse;
6035 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006036 case glslang::EOpRayQueryProceed:
6037 unaryOp = spv::OpRayQueryProceedKHR;
6038 break;
6039 case glslang::EOpRayQueryGetRayTMin:
6040 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6041 break;
6042 case glslang::EOpRayQueryGetRayFlags:
6043 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6044 break;
6045 case glslang::EOpRayQueryGetWorldRayOrigin:
6046 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6047 break;
6048 case glslang::EOpRayQueryGetWorldRayDirection:
6049 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6050 break;
6051 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6052 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6053 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006054 case glslang::EOpInterpolateAtCentroid:
6055 if (typeProxy == glslang::EbtFloat16)
6056 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6057 libCall = spv::GLSLstd450InterpolateAtCentroid;
6058 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006059 case glslang::EOpAtomicCounterIncrement:
6060 case glslang::EOpAtomicCounterDecrement:
6061 case glslang::EOpAtomicCounter:
6062 {
6063 // Handle all of the atomics in one place, in createAtomicOperation()
6064 std::vector<spv::Id> operands;
6065 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006066 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006067 }
6068
John Kessenichfc51d282015-08-19 13:34:18 -06006069 case glslang::EOpBitFieldReverse:
6070 unaryOp = spv::OpBitReverse;
6071 break;
6072 case glslang::EOpBitCount:
6073 unaryOp = spv::OpBitCount;
6074 break;
6075 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006076 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006077 break;
6078 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006079 if (isUnsigned)
6080 libCall = spv::GLSLstd450FindUMsb;
6081 else
6082 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006083 break;
6084
Ian Romanickb3bd4022019-01-21 08:57:25 -08006085 case glslang::EOpCountLeadingZeros:
6086 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6087 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6088 unaryOp = spv::OpUCountLeadingZerosINTEL;
6089 break;
6090
6091 case glslang::EOpCountTrailingZeros:
6092 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6093 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6094 unaryOp = spv::OpUCountTrailingZerosINTEL;
6095 break;
6096
Rex Xu574ab042016-04-14 16:53:07 +08006097 case glslang::EOpBallot:
6098 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006099 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006100 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006101 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006102 case glslang::EOpMinInvocations:
6103 case glslang::EOpMaxInvocations:
6104 case glslang::EOpAddInvocations:
6105 case glslang::EOpMinInvocationsNonUniform:
6106 case glslang::EOpMaxInvocationsNonUniform:
6107 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006108 case glslang::EOpMinInvocationsInclusiveScan:
6109 case glslang::EOpMaxInvocationsInclusiveScan:
6110 case glslang::EOpAddInvocationsInclusiveScan:
6111 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6112 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6113 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6114 case glslang::EOpMinInvocationsExclusiveScan:
6115 case glslang::EOpMaxInvocationsExclusiveScan:
6116 case glslang::EOpAddInvocationsExclusiveScan:
6117 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6118 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6119 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006120 {
6121 std::vector<spv::Id> operands;
6122 operands.push_back(operand);
6123 return createInvocationsOperation(op, typeId, operands, typeProxy);
6124 }
John Kessenich66011cb2018-03-06 16:12:04 -07006125 case glslang::EOpSubgroupAll:
6126 case glslang::EOpSubgroupAny:
6127 case glslang::EOpSubgroupAllEqual:
6128 case glslang::EOpSubgroupBroadcastFirst:
6129 case glslang::EOpSubgroupBallot:
6130 case glslang::EOpSubgroupInverseBallot:
6131 case glslang::EOpSubgroupBallotBitCount:
6132 case glslang::EOpSubgroupBallotInclusiveBitCount:
6133 case glslang::EOpSubgroupBallotExclusiveBitCount:
6134 case glslang::EOpSubgroupBallotFindLSB:
6135 case glslang::EOpSubgroupBallotFindMSB:
6136 case glslang::EOpSubgroupAdd:
6137 case glslang::EOpSubgroupMul:
6138 case glslang::EOpSubgroupMin:
6139 case glslang::EOpSubgroupMax:
6140 case glslang::EOpSubgroupAnd:
6141 case glslang::EOpSubgroupOr:
6142 case glslang::EOpSubgroupXor:
6143 case glslang::EOpSubgroupInclusiveAdd:
6144 case glslang::EOpSubgroupInclusiveMul:
6145 case glslang::EOpSubgroupInclusiveMin:
6146 case glslang::EOpSubgroupInclusiveMax:
6147 case glslang::EOpSubgroupInclusiveAnd:
6148 case glslang::EOpSubgroupInclusiveOr:
6149 case glslang::EOpSubgroupInclusiveXor:
6150 case glslang::EOpSubgroupExclusiveAdd:
6151 case glslang::EOpSubgroupExclusiveMul:
6152 case glslang::EOpSubgroupExclusiveMin:
6153 case glslang::EOpSubgroupExclusiveMax:
6154 case glslang::EOpSubgroupExclusiveAnd:
6155 case glslang::EOpSubgroupExclusiveOr:
6156 case glslang::EOpSubgroupExclusiveXor:
6157 case glslang::EOpSubgroupQuadSwapHorizontal:
6158 case glslang::EOpSubgroupQuadSwapVertical:
6159 case glslang::EOpSubgroupQuadSwapDiagonal: {
6160 std::vector<spv::Id> operands;
6161 operands.push_back(operand);
6162 return createSubgroupOperation(op, typeId, operands, typeProxy);
6163 }
Rex Xu9d93a232016-05-05 12:30:44 +08006164 case glslang::EOpMbcnt:
6165 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6166 libCall = spv::MbcntAMD;
6167 break;
6168
6169 case glslang::EOpCubeFaceIndex:
6170 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6171 libCall = spv::CubeFaceIndexAMD;
6172 break;
6173
6174 case glslang::EOpCubeFaceCoord:
6175 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6176 libCall = spv::CubeFaceCoordAMD;
6177 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006178 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006179 unaryOp = spv::OpGroupNonUniformPartitionNV;
6180 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006181 case glslang::EOpConstructReference:
6182 unaryOp = spv::OpBitcast;
6183 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006184#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006185
6186 case glslang::EOpCopyObject:
6187 unaryOp = spv::OpCopyObject;
6188 break;
6189
John Kessenich140f3df2015-06-26 16:58:36 -06006190 default:
6191 return 0;
6192 }
6193
6194 spv::Id id;
6195 if (libCall >= 0) {
6196 std::vector<spv::Id> args;
6197 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006198 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006199 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006200 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006201 }
John Kessenich140f3df2015-06-26 16:58:36 -06006202
John Kessenichb9197c82019-08-11 07:41:45 -06006203 decorations.addNoContraction(builder, id);
6204 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006205 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006206}
6207
John Kessenich7a53f762016-01-20 11:19:27 -07006208// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006209spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6210 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006211{
6212 // Handle unary operations vector by vector.
6213 // The result type is the same type as the original type.
6214 // The algorithm is to:
6215 // - break the matrix into vectors
6216 // - apply the operation to each vector
6217 // - make a matrix out the vector results
6218
6219 // get the types sorted out
6220 int numCols = builder.getNumColumns(operand);
6221 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006222 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6223 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006224 std::vector<spv::Id> results;
6225
6226 // do each vector op
6227 for (int c = 0; c < numCols; ++c) {
6228 std::vector<unsigned int> indexes;
6229 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006230 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6231 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006232 decorations.addNoContraction(builder, destVec);
6233 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006234 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006235 }
6236
6237 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006238 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006239 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006240 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006241}
6242
John Kessenichad7645f2018-06-04 19:11:25 -06006243// For converting integers where both the bitwidth and the signedness could
6244// change, but only do the width change here. The caller is still responsible
6245// for the signedness conversion.
6246spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006247{
John Kessenichad7645f2018-06-04 19:11:25 -06006248 // Get the result type width, based on the type to convert to.
6249 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006250 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006251 case glslang::EOpConvInt16ToUint8:
6252 case glslang::EOpConvIntToUint8:
6253 case glslang::EOpConvInt64ToUint8:
6254 case glslang::EOpConvUint16ToInt8:
6255 case glslang::EOpConvUintToInt8:
6256 case glslang::EOpConvUint64ToInt8:
6257 width = 8;
6258 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006259 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006260 case glslang::EOpConvIntToUint16:
6261 case glslang::EOpConvInt64ToUint16:
6262 case glslang::EOpConvUint8ToInt16:
6263 case glslang::EOpConvUintToInt16:
6264 case glslang::EOpConvUint64ToInt16:
6265 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006266 break;
6267 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006268 case glslang::EOpConvInt16ToUint:
6269 case glslang::EOpConvInt64ToUint:
6270 case glslang::EOpConvUint8ToInt:
6271 case glslang::EOpConvUint16ToInt:
6272 case glslang::EOpConvUint64ToInt:
6273 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006274 break;
6275 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006276 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006277 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006278 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006279 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006280 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006281 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006282 break;
6283
6284 default:
6285 assert(false && "Default missing");
6286 break;
6287 }
6288
John Kessenichad7645f2018-06-04 19:11:25 -06006289 // Get the conversion operation and result type,
6290 // based on the target width, but the source type.
6291 spv::Id type = spv::NoType;
6292 spv::Op convOp = spv::OpNop;
6293 switch(op) {
6294 case glslang::EOpConvInt8ToUint16:
6295 case glslang::EOpConvInt8ToUint:
6296 case glslang::EOpConvInt8ToUint64:
6297 case glslang::EOpConvInt16ToUint8:
6298 case glslang::EOpConvInt16ToUint:
6299 case glslang::EOpConvInt16ToUint64:
6300 case glslang::EOpConvIntToUint8:
6301 case glslang::EOpConvIntToUint16:
6302 case glslang::EOpConvIntToUint64:
6303 case glslang::EOpConvInt64ToUint8:
6304 case glslang::EOpConvInt64ToUint16:
6305 case glslang::EOpConvInt64ToUint:
6306 convOp = spv::OpSConvert;
6307 type = builder.makeIntType(width);
6308 break;
6309 default:
6310 convOp = spv::OpUConvert;
6311 type = builder.makeUintType(width);
6312 break;
6313 }
6314
John Kessenich66011cb2018-03-06 16:12:04 -07006315 if (vectorSize > 0)
6316 type = builder.makeVectorType(type, vectorSize);
6317
John Kessenichad7645f2018-06-04 19:11:25 -06006318 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006319}
6320
John Kessenichead86222018-03-28 18:01:20 -06006321spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6322 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006323{
6324 spv::Op convOp = spv::OpNop;
6325 spv::Id zero = 0;
6326 spv::Id one = 0;
6327
6328 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6329
6330 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006331 case glslang::EOpConvIntToBool:
6332 case glslang::EOpConvUintToBool:
6333 zero = builder.makeUintConstant(0);
6334 zero = makeSmearedConstant(zero, vectorSize);
6335 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006336 case glslang::EOpConvFloatToBool:
6337 zero = builder.makeFloatConstant(0.0F);
6338 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006339 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006340 case glslang::EOpConvBoolToFloat:
6341 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006342 zero = builder.makeFloatConstant(0.0F);
6343 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006344 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006345
John Kessenich140f3df2015-06-26 16:58:36 -06006346 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006347 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006348#ifndef GLSLANG_WEB
6349 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006350 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006351 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006352 } else
6353#endif
6354 {
6355 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006356 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006357 }
Rex Xucabbb782017-03-24 13:41:14 +08006358
John Kessenich140f3df2015-06-26 16:58:36 -06006359 convOp = spv::OpSelect;
6360 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006361
John Kessenich140f3df2015-06-26 16:58:36 -06006362 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006363 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006364#ifndef GLSLANG_WEB
6365 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006366 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006367 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006368 } else
6369#endif
6370 {
6371 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006372 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006373 }
Rex Xucabbb782017-03-24 13:41:14 +08006374
John Kessenich140f3df2015-06-26 16:58:36 -06006375 convOp = spv::OpSelect;
6376 break;
6377
John Kessenich66011cb2018-03-06 16:12:04 -07006378 case glslang::EOpConvInt8ToFloat16:
6379 case glslang::EOpConvInt8ToFloat:
6380 case glslang::EOpConvInt8ToDouble:
6381 case glslang::EOpConvInt16ToFloat16:
6382 case glslang::EOpConvInt16ToFloat:
6383 case glslang::EOpConvInt16ToDouble:
6384 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006385 case glslang::EOpConvIntToFloat:
6386 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006387 case glslang::EOpConvInt64ToFloat:
6388 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006389 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006390 convOp = spv::OpConvertSToF;
6391 break;
6392
John Kessenich66011cb2018-03-06 16:12:04 -07006393 case glslang::EOpConvUint8ToFloat16:
6394 case glslang::EOpConvUint8ToFloat:
6395 case glslang::EOpConvUint8ToDouble:
6396 case glslang::EOpConvUint16ToFloat16:
6397 case glslang::EOpConvUint16ToFloat:
6398 case glslang::EOpConvUint16ToDouble:
6399 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006400 case glslang::EOpConvUintToFloat:
6401 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006402 case glslang::EOpConvUint64ToFloat:
6403 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006404 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006405 convOp = spv::OpConvertUToF;
6406 break;
6407
John Kessenich66011cb2018-03-06 16:12:04 -07006408 case glslang::EOpConvFloat16ToInt8:
6409 case glslang::EOpConvFloatToInt8:
6410 case glslang::EOpConvDoubleToInt8:
6411 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006412 case glslang::EOpConvFloatToInt16:
6413 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006414 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006415 case glslang::EOpConvFloatToInt:
6416 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006417 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006418 case glslang::EOpConvFloatToInt64:
6419 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006420 convOp = spv::OpConvertFToS;
6421 break;
6422
John Kessenich66011cb2018-03-06 16:12:04 -07006423 case glslang::EOpConvUint8ToInt8:
6424 case glslang::EOpConvInt8ToUint8:
6425 case glslang::EOpConvUint16ToInt16:
6426 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006427 case glslang::EOpConvUintToInt:
6428 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006429 case glslang::EOpConvUint64ToInt64:
6430 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006431 if (builder.isInSpecConstCodeGenMode()) {
6432 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006433#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006434 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6435 zero = builder.makeUint8Constant(0);
6436 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006437 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006438 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6439 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006440 } else
6441#endif
6442 {
Rex Xucabbb782017-03-24 13:41:14 +08006443 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006444 }
qining189b2032016-04-12 23:16:20 -04006445 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006446 // Use OpIAdd, instead of OpBitcast to do the conversion when
6447 // generating for OpSpecConstantOp instruction.
6448 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6449 }
6450 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006451 convOp = spv::OpBitcast;
6452 break;
6453
John Kessenich66011cb2018-03-06 16:12:04 -07006454 case glslang::EOpConvFloat16ToUint8:
6455 case glslang::EOpConvFloatToUint8:
6456 case glslang::EOpConvDoubleToUint8:
6457 case glslang::EOpConvFloat16ToUint16:
6458 case glslang::EOpConvFloatToUint16:
6459 case glslang::EOpConvDoubleToUint16:
6460 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006461 case glslang::EOpConvFloatToUint:
6462 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006463 case glslang::EOpConvFloatToUint64:
6464 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006465 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006466 convOp = spv::OpConvertFToU;
6467 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006468
John Kessenich39697cd2019-08-08 10:35:51 -06006469#ifndef GLSLANG_WEB
6470 case glslang::EOpConvInt8ToBool:
6471 case glslang::EOpConvUint8ToBool:
6472 zero = builder.makeUint8Constant(0);
6473 zero = makeSmearedConstant(zero, vectorSize);
6474 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6475 case glslang::EOpConvInt16ToBool:
6476 case glslang::EOpConvUint16ToBool:
6477 zero = builder.makeUint16Constant(0);
6478 zero = makeSmearedConstant(zero, vectorSize);
6479 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6480 case glslang::EOpConvInt64ToBool:
6481 case glslang::EOpConvUint64ToBool:
6482 zero = builder.makeUint64Constant(0);
6483 zero = makeSmearedConstant(zero, vectorSize);
6484 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6485 case glslang::EOpConvDoubleToBool:
6486 zero = builder.makeDoubleConstant(0.0);
6487 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006488 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006489 case glslang::EOpConvFloat16ToBool:
6490 zero = builder.makeFloat16Constant(0.0F);
6491 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006492 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006493 case glslang::EOpConvBoolToDouble:
6494 convOp = spv::OpSelect;
6495 zero = builder.makeDoubleConstant(0.0);
6496 one = builder.makeDoubleConstant(1.0);
6497 break;
6498 case glslang::EOpConvBoolToFloat16:
6499 convOp = spv::OpSelect;
6500 zero = builder.makeFloat16Constant(0.0F);
6501 one = builder.makeFloat16Constant(1.0F);
6502 break;
6503 case glslang::EOpConvBoolToInt8:
6504 zero = builder.makeInt8Constant(0);
6505 one = builder.makeInt8Constant(1);
6506 convOp = spv::OpSelect;
6507 break;
6508 case glslang::EOpConvBoolToUint8:
6509 zero = builder.makeUint8Constant(0);
6510 one = builder.makeUint8Constant(1);
6511 convOp = spv::OpSelect;
6512 break;
6513 case glslang::EOpConvBoolToInt16:
6514 zero = builder.makeInt16Constant(0);
6515 one = builder.makeInt16Constant(1);
6516 convOp = spv::OpSelect;
6517 break;
6518 case glslang::EOpConvBoolToUint16:
6519 zero = builder.makeUint16Constant(0);
6520 one = builder.makeUint16Constant(1);
6521 convOp = spv::OpSelect;
6522 break;
6523 case glslang::EOpConvDoubleToFloat:
6524 case glslang::EOpConvFloatToDouble:
6525 case glslang::EOpConvDoubleToFloat16:
6526 case glslang::EOpConvFloat16ToDouble:
6527 case glslang::EOpConvFloatToFloat16:
6528 case glslang::EOpConvFloat16ToFloat:
6529 convOp = spv::OpFConvert;
6530 if (builder.isMatrixType(destType))
6531 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6532 break;
6533
John Kessenich66011cb2018-03-06 16:12:04 -07006534 case glslang::EOpConvInt8ToInt16:
6535 case glslang::EOpConvInt8ToInt:
6536 case glslang::EOpConvInt8ToInt64:
6537 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006538 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006539 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006540 case glslang::EOpConvIntToInt8:
6541 case glslang::EOpConvIntToInt16:
6542 case glslang::EOpConvIntToInt64:
6543 case glslang::EOpConvInt64ToInt8:
6544 case glslang::EOpConvInt64ToInt16:
6545 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006546 convOp = spv::OpSConvert;
6547 break;
6548
John Kessenich66011cb2018-03-06 16:12:04 -07006549 case glslang::EOpConvUint8ToUint16:
6550 case glslang::EOpConvUint8ToUint:
6551 case glslang::EOpConvUint8ToUint64:
6552 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006553 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006554 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006555 case glslang::EOpConvUintToUint8:
6556 case glslang::EOpConvUintToUint16:
6557 case glslang::EOpConvUintToUint64:
6558 case glslang::EOpConvUint64ToUint8:
6559 case glslang::EOpConvUint64ToUint16:
6560 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006561 convOp = spv::OpUConvert;
6562 break;
6563
John Kessenich66011cb2018-03-06 16:12:04 -07006564 case glslang::EOpConvInt8ToUint16:
6565 case glslang::EOpConvInt8ToUint:
6566 case glslang::EOpConvInt8ToUint64:
6567 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006568 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006569 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006570 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006571 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006572 case glslang::EOpConvIntToUint64:
6573 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006574 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006575 case glslang::EOpConvInt64ToUint:
6576 case glslang::EOpConvUint8ToInt16:
6577 case glslang::EOpConvUint8ToInt:
6578 case glslang::EOpConvUint8ToInt64:
6579 case glslang::EOpConvUint16ToInt8:
6580 case glslang::EOpConvUint16ToInt:
6581 case glslang::EOpConvUint16ToInt64:
6582 case glslang::EOpConvUintToInt8:
6583 case glslang::EOpConvUintToInt16:
6584 case glslang::EOpConvUintToInt64:
6585 case glslang::EOpConvUint64ToInt8:
6586 case glslang::EOpConvUint64ToInt16:
6587 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006588 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006589 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006590
6591 if (builder.isInSpecConstCodeGenMode()) {
6592 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006593 switch(op) {
6594 case glslang::EOpConvInt16ToUint8:
6595 case glslang::EOpConvIntToUint8:
6596 case glslang::EOpConvInt64ToUint8:
6597 case glslang::EOpConvUint16ToInt8:
6598 case glslang::EOpConvUintToInt8:
6599 case glslang::EOpConvUint64ToInt8:
6600 zero = builder.makeUint8Constant(0);
6601 break;
6602 case glslang::EOpConvInt8ToUint16:
6603 case glslang::EOpConvIntToUint16:
6604 case glslang::EOpConvInt64ToUint16:
6605 case glslang::EOpConvUint8ToInt16:
6606 case glslang::EOpConvUintToInt16:
6607 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006608 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006609 break;
6610 case glslang::EOpConvInt8ToUint:
6611 case glslang::EOpConvInt16ToUint:
6612 case glslang::EOpConvInt64ToUint:
6613 case glslang::EOpConvUint8ToInt:
6614 case glslang::EOpConvUint16ToInt:
6615 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006616 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006617 break;
6618 case glslang::EOpConvInt8ToUint64:
6619 case glslang::EOpConvInt16ToUint64:
6620 case glslang::EOpConvIntToUint64:
6621 case glslang::EOpConvUint8ToInt64:
6622 case glslang::EOpConvUint16ToInt64:
6623 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006624 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006625 break;
6626 default:
6627 assert(false && "Default missing");
6628 break;
6629 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006630 zero = makeSmearedConstant(zero, vectorSize);
6631 // Use OpIAdd, instead of OpBitcast to do the conversion when
6632 // generating for OpSpecConstantOp instruction.
6633 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6634 }
6635 // For normal run-time conversion instruction, use OpBitcast.
6636 convOp = spv::OpBitcast;
6637 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006638 case glslang::EOpConvUint64ToPtr:
6639 convOp = spv::OpConvertUToPtr;
6640 break;
6641 case glslang::EOpConvPtrToUint64:
6642 convOp = spv::OpConvertPtrToU;
6643 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006644 case glslang::EOpConvPtrToUvec2:
6645 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006646 if (builder.isVector(operand))
6647 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6648 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006649 convOp = spv::OpBitcast;
6650 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006651#endif
6652
John Kessenich140f3df2015-06-26 16:58:36 -06006653 default:
6654 break;
6655 }
6656
6657 spv::Id result = 0;
6658 if (convOp == spv::OpNop)
6659 return result;
6660
6661 if (convOp == spv::OpSelect) {
6662 zero = makeSmearedConstant(zero, vectorSize);
6663 one = makeSmearedConstant(one, vectorSize);
6664 result = builder.createTriOp(convOp, destType, operand, one, zero);
6665 } else
6666 result = builder.createUnaryOp(convOp, destType, operand);
6667
John Kessenichead86222018-03-28 18:01:20 -06006668 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006669 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006670 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006671}
6672
6673spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6674{
6675 if (vectorSize == 0)
6676 return constant;
6677
6678 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6679 std::vector<spv::Id> components;
6680 for (int c = 0; c < vectorSize; ++c)
6681 components.push_back(constant);
6682 return builder.makeCompositeConstant(vectorTypeId, components);
6683}
6684
John Kessenich426394d2015-07-23 10:22:48 -06006685// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006686spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6687 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6688 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006689{
6690 spv::Op opCode = spv::OpNop;
6691
6692 switch (op) {
6693 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006694 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006695 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006696 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006697 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6698 opCode = spv::OpAtomicFAddEXT;
6699 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6700 if (typeProxy == glslang::EbtFloat)
6701 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6702 else
6703 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6704 }
John Kessenich426394d2015-07-23 10:22:48 -06006705 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006706 case glslang::EOpAtomicCounterSubtract:
6707 opCode = spv::OpAtomicISub;
6708 break;
John Kessenich426394d2015-07-23 10:22:48 -06006709 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006710 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006711 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006712 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6713 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006714 break;
6715 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006716 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006717 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006718 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6719 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006720 break;
6721 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006722 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006723 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006724 opCode = spv::OpAtomicAnd;
6725 break;
6726 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006727 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006728 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006729 opCode = spv::OpAtomicOr;
6730 break;
6731 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006732 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006733 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006734 opCode = spv::OpAtomicXor;
6735 break;
6736 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006737 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006738 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006739 opCode = spv::OpAtomicExchange;
6740 break;
6741 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006742 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006743 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006744 opCode = spv::OpAtomicCompareExchange;
6745 break;
6746 case glslang::EOpAtomicCounterIncrement:
6747 opCode = spv::OpAtomicIIncrement;
6748 break;
6749 case glslang::EOpAtomicCounterDecrement:
6750 opCode = spv::OpAtomicIDecrement;
6751 break;
6752 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006753 case glslang::EOpImageAtomicLoad:
6754 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006755 opCode = spv::OpAtomicLoad;
6756 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006757 case glslang::EOpAtomicStore:
6758 case glslang::EOpImageAtomicStore:
6759 opCode = spv::OpAtomicStore;
6760 break;
John Kessenich426394d2015-07-23 10:22:48 -06006761 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006762 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006763 break;
6764 }
6765
Rex Xue8fe8b02017-09-26 15:42:56 +08006766 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6767 builder.addCapability(spv::CapabilityInt64Atomics);
6768
John Kessenich426394d2015-07-23 10:22:48 -06006769 // Sort out the operands
6770 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006771 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006772 // - compare-exchange swaps the value and comparator
6773 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006774 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006775 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6776 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6777 spv::Id scopeId;
6778 if (glslangIntermediate->usingVulkanMemoryModel()) {
6779 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6780 } else {
6781 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6782 }
6783 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006784 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6785 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006786 spv::MemorySemanticsVolatileMask :
6787 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006788 spv::Id semanticsId2 = semanticsId;
6789
6790 pointerId = operands[0];
6791 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6792 // no additional operands
6793 } else if (opCode == spv::OpAtomicCompareExchange) {
6794 compareId = operands[1];
6795 valueId = operands[2];
6796 if (operands.size() > 3) {
6797 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006798 semanticsId = builder.makeUintConstant(
6799 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6800 semanticsId2 = builder.makeUintConstant(
6801 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006802 }
6803 } else if (opCode == spv::OpAtomicLoad) {
6804 if (operands.size() > 1) {
6805 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006806 semanticsId = builder.makeUintConstant(
6807 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006808 }
6809 } else {
6810 // atomic store or RMW
6811 valueId = operands[1];
6812 if (operands.size() > 2) {
6813 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006814 semanticsId = builder.makeUintConstant
6815 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006816 }
Rex Xu04db3f52015-09-16 11:44:02 +08006817 }
John Kessenich426394d2015-07-23 10:22:48 -06006818
Jeff Bolz36831c92018-09-05 10:11:41 -05006819 // Check for capabilities
6820 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006821 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6822 spv::MemorySemanticsMakeVisibleKHRMask |
6823 spv::MemorySemanticsOutputMemoryKHRMask |
6824 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006825 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6826 }
John Kessenich426394d2015-07-23 10:22:48 -06006827
Jeff Bolz36831c92018-09-05 10:11:41 -05006828 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6829 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6830 }
John Kessenich48d6e792017-10-06 21:21:48 -06006831
Jeff Bolz36831c92018-09-05 10:11:41 -05006832 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6833 spvAtomicOperands.push_back(pointerId);
6834 spvAtomicOperands.push_back(scopeId);
6835 spvAtomicOperands.push_back(semanticsId);
6836 if (opCode == spv::OpAtomicCompareExchange) {
6837 spvAtomicOperands.push_back(semanticsId2);
6838 spvAtomicOperands.push_back(valueId);
6839 spvAtomicOperands.push_back(compareId);
6840 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6841 spvAtomicOperands.push_back(valueId);
6842 }
John Kessenich48d6e792017-10-06 21:21:48 -06006843
Jeff Bolz36831c92018-09-05 10:11:41 -05006844 if (opCode == spv::OpAtomicStore) {
6845 builder.createNoResultOp(opCode, spvAtomicOperands);
6846 return 0;
6847 } else {
6848 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6849
6850 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6851 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6852 if (op == glslang::EOpAtomicCounterDecrement)
6853 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6854
6855 return resultId;
6856 }
John Kessenich426394d2015-07-23 10:22:48 -06006857}
6858
John Kessenich91cef522016-05-05 16:45:40 -06006859// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006860spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6861 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006862{
John Kessenich66011cb2018-03-06 16:12:04 -07006863 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6864 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006865
Rex Xu51596642016-09-21 18:56:12 +08006866 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006867 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006868 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6869
chaocf200da82016-12-20 12:44:35 -08006870 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6871 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006872 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6873 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006874 } else if (op == glslang::EOpAnyInvocation ||
6875 op == glslang::EOpAllInvocations ||
6876 op == glslang::EOpAllInvocationsEqual) {
6877 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6878 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006879 } else {
6880 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006881 if (op == glslang::EOpMinInvocationsNonUniform ||
6882 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006883 op == glslang::EOpAddInvocationsNonUniform ||
6884 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6885 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6886 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6887 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6888 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6889 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006890 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006891
Rex Xu430ef402016-10-14 17:22:23 +08006892 switch (op) {
6893 case glslang::EOpMinInvocations:
6894 case glslang::EOpMaxInvocations:
6895 case glslang::EOpAddInvocations:
6896 case glslang::EOpMinInvocationsNonUniform:
6897 case glslang::EOpMaxInvocationsNonUniform:
6898 case glslang::EOpAddInvocationsNonUniform:
6899 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006900 break;
6901 case glslang::EOpMinInvocationsInclusiveScan:
6902 case glslang::EOpMaxInvocationsInclusiveScan:
6903 case glslang::EOpAddInvocationsInclusiveScan:
6904 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6905 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6906 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6907 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006908 break;
6909 case glslang::EOpMinInvocationsExclusiveScan:
6910 case glslang::EOpMaxInvocationsExclusiveScan:
6911 case glslang::EOpAddInvocationsExclusiveScan:
6912 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6913 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6914 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6915 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006916 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006917 default:
6918 break;
Rex Xu430ef402016-10-14 17:22:23 +08006919 }
John Kessenich149afc32018-08-14 13:31:43 -06006920 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6921 spvGroupOperands.push_back(scope);
6922 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006923 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006924 spvGroupOperands.push_back(groupOp);
6925 }
Rex Xu51596642016-09-21 18:56:12 +08006926 }
6927
John Kessenich149afc32018-08-14 13:31:43 -06006928 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6929 spv::IdImmediate op = { true, *opIt };
6930 spvGroupOperands.push_back(op);
6931 }
John Kessenich91cef522016-05-05 16:45:40 -06006932
6933 switch (op) {
6934 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006935 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006936 break;
John Kessenich91cef522016-05-05 16:45:40 -06006937 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006938 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006939 break;
John Kessenich91cef522016-05-05 16:45:40 -06006940 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006941 opCode = spv::OpSubgroupAllEqualKHR;
6942 break;
Rex Xu51596642016-09-21 18:56:12 +08006943 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006944 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006945 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006946 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006947 break;
6948 case glslang::EOpReadFirstInvocation:
6949 opCode = spv::OpSubgroupFirstInvocationKHR;
6950 break;
6951 case glslang::EOpBallot:
6952 {
6953 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6954 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6955 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6956 //
6957 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6958 //
6959 spv::Id uintType = builder.makeUintType(32);
6960 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6961 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6962
6963 std::vector<spv::Id> components;
6964 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6965 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6966
6967 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6968 return builder.createUnaryOp(spv::OpBitcast, typeId,
6969 builder.createCompositeConstruct(uvec2Type, components));
6970 }
6971
Rex Xu9d93a232016-05-05 12:30:44 +08006972 case glslang::EOpMinInvocations:
6973 case glslang::EOpMaxInvocations:
6974 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006975 case glslang::EOpMinInvocationsInclusiveScan:
6976 case glslang::EOpMaxInvocationsInclusiveScan:
6977 case glslang::EOpAddInvocationsInclusiveScan:
6978 case glslang::EOpMinInvocationsExclusiveScan:
6979 case glslang::EOpMaxInvocationsExclusiveScan:
6980 case glslang::EOpAddInvocationsExclusiveScan:
6981 if (op == glslang::EOpMinInvocations ||
6982 op == glslang::EOpMinInvocationsInclusiveScan ||
6983 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006984 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006985 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006986 else {
6987 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006988 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006989 else
Rex Xu51596642016-09-21 18:56:12 +08006990 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006991 }
Rex Xu430ef402016-10-14 17:22:23 +08006992 } else if (op == glslang::EOpMaxInvocations ||
6993 op == glslang::EOpMaxInvocationsInclusiveScan ||
6994 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006995 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006996 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006997 else {
6998 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006999 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007000 else
Rex Xu51596642016-09-21 18:56:12 +08007001 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007002 }
7003 } else {
7004 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007005 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007006 else
Rex Xu51596642016-09-21 18:56:12 +08007007 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007008 }
7009
Rex Xu2bbbe062016-08-23 15:41:05 +08007010 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007011 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007012
7013 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007014 case glslang::EOpMinInvocationsNonUniform:
7015 case glslang::EOpMaxInvocationsNonUniform:
7016 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007017 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7018 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7019 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7020 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7021 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7022 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7023 if (op == glslang::EOpMinInvocationsNonUniform ||
7024 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7025 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007026 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007027 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007028 else {
7029 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007030 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007031 else
Rex Xu51596642016-09-21 18:56:12 +08007032 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007033 }
7034 }
Rex Xu430ef402016-10-14 17:22:23 +08007035 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7036 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7037 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007038 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007039 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007040 else {
7041 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007042 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007043 else
Rex Xu51596642016-09-21 18:56:12 +08007044 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007045 }
7046 }
7047 else {
7048 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007049 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007050 else
Rex Xu51596642016-09-21 18:56:12 +08007051 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007052 }
7053
Rex Xu2bbbe062016-08-23 15:41:05 +08007054 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007055 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007056
7057 break;
John Kessenich91cef522016-05-05 16:45:40 -06007058 default:
7059 logger->missingFunctionality("invocation operation");
7060 return spv::NoResult;
7061 }
Rex Xu51596642016-09-21 18:56:12 +08007062
7063 assert(opCode != spv::OpNop);
7064 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007065}
7066
Rex Xu2bbbe062016-08-23 15:41:05 +08007067// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007068spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7069 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007070{
7071 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7072 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007073 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007074 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007075 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7076 op == spv::OpGroupSMinNonUniformAMD ||
7077 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7078 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007079 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7080
7081 // Handle group invocation operations scalar by scalar.
7082 // The result type is the same type as the original type.
7083 // The algorithm is to:
7084 // - break the vector into scalars
7085 // - apply the operation to each scalar
7086 // - make a vector out the scalar results
7087
7088 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007089 int numComponents = builder.getNumComponents(operands[0]);
7090 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007091 std::vector<spv::Id> results;
7092
7093 // do each scalar op
7094 for (int comp = 0; comp < numComponents; ++comp) {
7095 std::vector<unsigned int> indexes;
7096 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007097 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7098 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007099 if (op == spv::OpSubgroupReadInvocationKHR) {
7100 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007101 spv::IdImmediate operand = { true, operands[1] };
7102 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007103 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007104 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7105 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007106 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007107 spv::IdImmediate operand = { true, operands[1] };
7108 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007109 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007110 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7111 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007112 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007113 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007114 spvGroupOperands.push_back(scalar);
7115 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007116
Rex Xub7072052016-09-26 15:53:40 +08007117 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007118 }
7119
7120 // put the pieces together
7121 return builder.createCompositeConstruct(typeId, results);
7122}
Rex Xu2bbbe062016-08-23 15:41:05 +08007123
John Kessenich66011cb2018-03-06 16:12:04 -07007124// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007125spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7126 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007127{
7128 // Add the required capabilities.
7129 switch (op) {
7130 case glslang::EOpSubgroupElect:
7131 builder.addCapability(spv::CapabilityGroupNonUniform);
7132 break;
7133 case glslang::EOpSubgroupAll:
7134 case glslang::EOpSubgroupAny:
7135 case glslang::EOpSubgroupAllEqual:
7136 builder.addCapability(spv::CapabilityGroupNonUniform);
7137 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7138 break;
7139 case glslang::EOpSubgroupBroadcast:
7140 case glslang::EOpSubgroupBroadcastFirst:
7141 case glslang::EOpSubgroupBallot:
7142 case glslang::EOpSubgroupInverseBallot:
7143 case glslang::EOpSubgroupBallotBitExtract:
7144 case glslang::EOpSubgroupBallotBitCount:
7145 case glslang::EOpSubgroupBallotInclusiveBitCount:
7146 case glslang::EOpSubgroupBallotExclusiveBitCount:
7147 case glslang::EOpSubgroupBallotFindLSB:
7148 case glslang::EOpSubgroupBallotFindMSB:
7149 builder.addCapability(spv::CapabilityGroupNonUniform);
7150 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7151 break;
7152 case glslang::EOpSubgroupShuffle:
7153 case glslang::EOpSubgroupShuffleXor:
7154 builder.addCapability(spv::CapabilityGroupNonUniform);
7155 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7156 break;
7157 case glslang::EOpSubgroupShuffleUp:
7158 case glslang::EOpSubgroupShuffleDown:
7159 builder.addCapability(spv::CapabilityGroupNonUniform);
7160 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7161 break;
7162 case glslang::EOpSubgroupAdd:
7163 case glslang::EOpSubgroupMul:
7164 case glslang::EOpSubgroupMin:
7165 case glslang::EOpSubgroupMax:
7166 case glslang::EOpSubgroupAnd:
7167 case glslang::EOpSubgroupOr:
7168 case glslang::EOpSubgroupXor:
7169 case glslang::EOpSubgroupInclusiveAdd:
7170 case glslang::EOpSubgroupInclusiveMul:
7171 case glslang::EOpSubgroupInclusiveMin:
7172 case glslang::EOpSubgroupInclusiveMax:
7173 case glslang::EOpSubgroupInclusiveAnd:
7174 case glslang::EOpSubgroupInclusiveOr:
7175 case glslang::EOpSubgroupInclusiveXor:
7176 case glslang::EOpSubgroupExclusiveAdd:
7177 case glslang::EOpSubgroupExclusiveMul:
7178 case glslang::EOpSubgroupExclusiveMin:
7179 case glslang::EOpSubgroupExclusiveMax:
7180 case glslang::EOpSubgroupExclusiveAnd:
7181 case glslang::EOpSubgroupExclusiveOr:
7182 case glslang::EOpSubgroupExclusiveXor:
7183 builder.addCapability(spv::CapabilityGroupNonUniform);
7184 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7185 break;
7186 case glslang::EOpSubgroupClusteredAdd:
7187 case glslang::EOpSubgroupClusteredMul:
7188 case glslang::EOpSubgroupClusteredMin:
7189 case glslang::EOpSubgroupClusteredMax:
7190 case glslang::EOpSubgroupClusteredAnd:
7191 case glslang::EOpSubgroupClusteredOr:
7192 case glslang::EOpSubgroupClusteredXor:
7193 builder.addCapability(spv::CapabilityGroupNonUniform);
7194 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7195 break;
7196 case glslang::EOpSubgroupQuadBroadcast:
7197 case glslang::EOpSubgroupQuadSwapHorizontal:
7198 case glslang::EOpSubgroupQuadSwapVertical:
7199 case glslang::EOpSubgroupQuadSwapDiagonal:
7200 builder.addCapability(spv::CapabilityGroupNonUniform);
7201 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7202 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007203 case glslang::EOpSubgroupPartitionedAdd:
7204 case glslang::EOpSubgroupPartitionedMul:
7205 case glslang::EOpSubgroupPartitionedMin:
7206 case glslang::EOpSubgroupPartitionedMax:
7207 case glslang::EOpSubgroupPartitionedAnd:
7208 case glslang::EOpSubgroupPartitionedOr:
7209 case glslang::EOpSubgroupPartitionedXor:
7210 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7211 case glslang::EOpSubgroupPartitionedInclusiveMul:
7212 case glslang::EOpSubgroupPartitionedInclusiveMin:
7213 case glslang::EOpSubgroupPartitionedInclusiveMax:
7214 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7215 case glslang::EOpSubgroupPartitionedInclusiveOr:
7216 case glslang::EOpSubgroupPartitionedInclusiveXor:
7217 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7218 case glslang::EOpSubgroupPartitionedExclusiveMul:
7219 case glslang::EOpSubgroupPartitionedExclusiveMin:
7220 case glslang::EOpSubgroupPartitionedExclusiveMax:
7221 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7222 case glslang::EOpSubgroupPartitionedExclusiveOr:
7223 case glslang::EOpSubgroupPartitionedExclusiveXor:
7224 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7225 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7226 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007227 default: assert(0 && "Unhandled subgroup operation!");
7228 }
7229
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007230
7231 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7232 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007233 const bool isBool = typeProxy == glslang::EbtBool;
7234
7235 spv::Op opCode = spv::OpNop;
7236
7237 // Figure out which opcode to use.
7238 switch (op) {
7239 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7240 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7241 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7242 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7243 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7244 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7245 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7246 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7247 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7248 case glslang::EOpSubgroupBallotBitCount:
7249 case glslang::EOpSubgroupBallotInclusiveBitCount:
7250 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7251 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7252 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7253 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7254 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7255 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7256 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7257 case glslang::EOpSubgroupAdd:
7258 case glslang::EOpSubgroupInclusiveAdd:
7259 case glslang::EOpSubgroupExclusiveAdd:
7260 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007261 case glslang::EOpSubgroupPartitionedAdd:
7262 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7263 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007264 if (isFloat) {
7265 opCode = spv::OpGroupNonUniformFAdd;
7266 } else {
7267 opCode = spv::OpGroupNonUniformIAdd;
7268 }
7269 break;
7270 case glslang::EOpSubgroupMul:
7271 case glslang::EOpSubgroupInclusiveMul:
7272 case glslang::EOpSubgroupExclusiveMul:
7273 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007274 case glslang::EOpSubgroupPartitionedMul:
7275 case glslang::EOpSubgroupPartitionedInclusiveMul:
7276 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007277 if (isFloat) {
7278 opCode = spv::OpGroupNonUniformFMul;
7279 } else {
7280 opCode = spv::OpGroupNonUniformIMul;
7281 }
7282 break;
7283 case glslang::EOpSubgroupMin:
7284 case glslang::EOpSubgroupInclusiveMin:
7285 case glslang::EOpSubgroupExclusiveMin:
7286 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007287 case glslang::EOpSubgroupPartitionedMin:
7288 case glslang::EOpSubgroupPartitionedInclusiveMin:
7289 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007290 if (isFloat) {
7291 opCode = spv::OpGroupNonUniformFMin;
7292 } else if (isUnsigned) {
7293 opCode = spv::OpGroupNonUniformUMin;
7294 } else {
7295 opCode = spv::OpGroupNonUniformSMin;
7296 }
7297 break;
7298 case glslang::EOpSubgroupMax:
7299 case glslang::EOpSubgroupInclusiveMax:
7300 case glslang::EOpSubgroupExclusiveMax:
7301 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007302 case glslang::EOpSubgroupPartitionedMax:
7303 case glslang::EOpSubgroupPartitionedInclusiveMax:
7304 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007305 if (isFloat) {
7306 opCode = spv::OpGroupNonUniformFMax;
7307 } else if (isUnsigned) {
7308 opCode = spv::OpGroupNonUniformUMax;
7309 } else {
7310 opCode = spv::OpGroupNonUniformSMax;
7311 }
7312 break;
7313 case glslang::EOpSubgroupAnd:
7314 case glslang::EOpSubgroupInclusiveAnd:
7315 case glslang::EOpSubgroupExclusiveAnd:
7316 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007317 case glslang::EOpSubgroupPartitionedAnd:
7318 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7319 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007320 if (isBool) {
7321 opCode = spv::OpGroupNonUniformLogicalAnd;
7322 } else {
7323 opCode = spv::OpGroupNonUniformBitwiseAnd;
7324 }
7325 break;
7326 case glslang::EOpSubgroupOr:
7327 case glslang::EOpSubgroupInclusiveOr:
7328 case glslang::EOpSubgroupExclusiveOr:
7329 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007330 case glslang::EOpSubgroupPartitionedOr:
7331 case glslang::EOpSubgroupPartitionedInclusiveOr:
7332 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007333 if (isBool) {
7334 opCode = spv::OpGroupNonUniformLogicalOr;
7335 } else {
7336 opCode = spv::OpGroupNonUniformBitwiseOr;
7337 }
7338 break;
7339 case glslang::EOpSubgroupXor:
7340 case glslang::EOpSubgroupInclusiveXor:
7341 case glslang::EOpSubgroupExclusiveXor:
7342 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007343 case glslang::EOpSubgroupPartitionedXor:
7344 case glslang::EOpSubgroupPartitionedInclusiveXor:
7345 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007346 if (isBool) {
7347 opCode = spv::OpGroupNonUniformLogicalXor;
7348 } else {
7349 opCode = spv::OpGroupNonUniformBitwiseXor;
7350 }
7351 break;
7352 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7353 case glslang::EOpSubgroupQuadSwapHorizontal:
7354 case glslang::EOpSubgroupQuadSwapVertical:
7355 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7356 default: assert(0 && "Unhandled subgroup operation!");
7357 }
7358
John Kessenich149afc32018-08-14 13:31:43 -06007359 // get the right Group Operation
7360 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007361 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007362 default:
7363 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007364 case glslang::EOpSubgroupBallotBitCount:
7365 case glslang::EOpSubgroupAdd:
7366 case glslang::EOpSubgroupMul:
7367 case glslang::EOpSubgroupMin:
7368 case glslang::EOpSubgroupMax:
7369 case glslang::EOpSubgroupAnd:
7370 case glslang::EOpSubgroupOr:
7371 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007372 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007373 break;
7374 case glslang::EOpSubgroupBallotInclusiveBitCount:
7375 case glslang::EOpSubgroupInclusiveAdd:
7376 case glslang::EOpSubgroupInclusiveMul:
7377 case glslang::EOpSubgroupInclusiveMin:
7378 case glslang::EOpSubgroupInclusiveMax:
7379 case glslang::EOpSubgroupInclusiveAnd:
7380 case glslang::EOpSubgroupInclusiveOr:
7381 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007382 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007383 break;
7384 case glslang::EOpSubgroupBallotExclusiveBitCount:
7385 case glslang::EOpSubgroupExclusiveAdd:
7386 case glslang::EOpSubgroupExclusiveMul:
7387 case glslang::EOpSubgroupExclusiveMin:
7388 case glslang::EOpSubgroupExclusiveMax:
7389 case glslang::EOpSubgroupExclusiveAnd:
7390 case glslang::EOpSubgroupExclusiveOr:
7391 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007392 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007393 break;
7394 case glslang::EOpSubgroupClusteredAdd:
7395 case glslang::EOpSubgroupClusteredMul:
7396 case glslang::EOpSubgroupClusteredMin:
7397 case glslang::EOpSubgroupClusteredMax:
7398 case glslang::EOpSubgroupClusteredAnd:
7399 case glslang::EOpSubgroupClusteredOr:
7400 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007401 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007402 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007403 case glslang::EOpSubgroupPartitionedAdd:
7404 case glslang::EOpSubgroupPartitionedMul:
7405 case glslang::EOpSubgroupPartitionedMin:
7406 case glslang::EOpSubgroupPartitionedMax:
7407 case glslang::EOpSubgroupPartitionedAnd:
7408 case glslang::EOpSubgroupPartitionedOr:
7409 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007410 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007411 break;
7412 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7413 case glslang::EOpSubgroupPartitionedInclusiveMul:
7414 case glslang::EOpSubgroupPartitionedInclusiveMin:
7415 case glslang::EOpSubgroupPartitionedInclusiveMax:
7416 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7417 case glslang::EOpSubgroupPartitionedInclusiveOr:
7418 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007419 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007420 break;
7421 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7422 case glslang::EOpSubgroupPartitionedExclusiveMul:
7423 case glslang::EOpSubgroupPartitionedExclusiveMin:
7424 case glslang::EOpSubgroupPartitionedExclusiveMax:
7425 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7426 case glslang::EOpSubgroupPartitionedExclusiveOr:
7427 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007428 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007429 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007430 }
7431
John Kessenich149afc32018-08-14 13:31:43 -06007432 // build the instruction
7433 std::vector<spv::IdImmediate> spvGroupOperands;
7434
7435 // Every operation begins with the Execution Scope operand.
7436 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7437 spvGroupOperands.push_back(executionScope);
7438
7439 // Next, for all operations that use a Group Operation, push that as an operand.
7440 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007441 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007442 spvGroupOperands.push_back(groupOperand);
7443 }
7444
John Kessenich66011cb2018-03-06 16:12:04 -07007445 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007446 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7447 spv::IdImmediate operand = { true, *opIt };
7448 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007449 }
7450
7451 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007452 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007453 switch (op) {
7454 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007455 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7456 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7457 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7458 }
7459 if (directionId != spv::NoResult) {
7460 spv::IdImmediate direction = { true, directionId };
7461 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007462 }
7463
7464 return builder.createOp(opCode, typeId, spvGroupOperands);
7465}
7466
John Kessenich8985fc92020-03-03 10:25:07 -07007467spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7468 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007469{
John Kessenich66011cb2018-03-06 16:12:04 -07007470 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7471 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007472
John Kessenich140f3df2015-06-26 16:58:36 -06007473 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007474 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007475 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007476 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007477 spv::Id typeId0 = 0;
7478 if (consumedOperands > 0)
7479 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007480 spv::Id typeId1 = 0;
7481 if (consumedOperands > 1)
7482 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007483 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007484
7485 switch (op) {
7486 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007487 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007488 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007489 else if (isUnsigned)
7490 libCall = spv::GLSLstd450UMin;
7491 else
7492 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007493 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007494 break;
7495 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007496 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007497 break;
7498 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007499 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007500 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007501 else if (isUnsigned)
7502 libCall = spv::GLSLstd450UMax;
7503 else
7504 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007505 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007506 break;
7507 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007508 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007509 break;
7510 case glslang::EOpDot:
7511 opCode = spv::OpDot;
7512 break;
7513 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007514 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007515 break;
7516
7517 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007518 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007519 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007520 else if (isUnsigned)
7521 libCall = spv::GLSLstd450UClamp;
7522 else
7523 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007524 builder.promoteScalar(precision, operands.front(), operands[1]);
7525 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007526 break;
7527 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007528 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7529 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007530 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007531 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007532 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007533 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007534 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007535 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007536 break;
7537 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007538 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007539 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007540 break;
7541 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007542 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007543 builder.promoteScalar(precision, operands[0], operands[2]);
7544 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007545 break;
7546
7547 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007548 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007549 break;
7550 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007551 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007552 break;
7553 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007554 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007555 break;
7556 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007557 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007558 break;
7559 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007560 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007561 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007562 case glslang::EOpBarrier:
7563 {
7564 // This is for the extended controlBarrier function, with four operands.
7565 // The unextended barrier() goes through createNoArgOperation.
7566 assert(operands.size() == 4);
7567 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7568 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7569 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007570 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7571 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007572 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7573 spv::MemorySemanticsMakeVisibleKHRMask |
7574 spv::MemorySemanticsOutputMemoryKHRMask |
7575 spv::MemorySemanticsVolatileMask)) {
7576 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7577 }
John Kessenich8985fc92020-03-03 10:25:07 -07007578 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7579 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007580 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7581 }
7582 return 0;
7583 }
7584 break;
7585 case glslang::EOpMemoryBarrier:
7586 {
7587 // This is for the extended memoryBarrier function, with three operands.
7588 // The unextended memoryBarrier() goes through createNoArgOperation.
7589 assert(operands.size() == 3);
7590 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7591 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7592 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7593 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7594 spv::MemorySemanticsMakeVisibleKHRMask |
7595 spv::MemorySemanticsOutputMemoryKHRMask |
7596 spv::MemorySemanticsVolatileMask)) {
7597 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7598 }
7599 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7600 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7601 }
7602 return 0;
7603 }
7604 break;
7605
John Kessenicha28f7a72019-08-06 07:00:58 -06007606#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007607 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007608 if (typeProxy == glslang::EbtFloat16)
7609 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007610 libCall = spv::GLSLstd450InterpolateAtSample;
7611 break;
7612 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007613 if (typeProxy == glslang::EbtFloat16)
7614 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007615 libCall = spv::GLSLstd450InterpolateAtOffset;
7616 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007617 case glslang::EOpAddCarry:
7618 opCode = spv::OpIAddCarry;
7619 typeId = builder.makeStructResultType(typeId0, typeId0);
7620 consumedOperands = 2;
7621 break;
7622 case glslang::EOpSubBorrow:
7623 opCode = spv::OpISubBorrow;
7624 typeId = builder.makeStructResultType(typeId0, typeId0);
7625 consumedOperands = 2;
7626 break;
7627 case glslang::EOpUMulExtended:
7628 opCode = spv::OpUMulExtended;
7629 typeId = builder.makeStructResultType(typeId0, typeId0);
7630 consumedOperands = 2;
7631 break;
7632 case glslang::EOpIMulExtended:
7633 opCode = spv::OpSMulExtended;
7634 typeId = builder.makeStructResultType(typeId0, typeId0);
7635 consumedOperands = 2;
7636 break;
7637 case glslang::EOpBitfieldExtract:
7638 if (isUnsigned)
7639 opCode = spv::OpBitFieldUExtract;
7640 else
7641 opCode = spv::OpBitFieldSExtract;
7642 break;
7643 case glslang::EOpBitfieldInsert:
7644 opCode = spv::OpBitFieldInsert;
7645 break;
7646
7647 case glslang::EOpFma:
7648 libCall = spv::GLSLstd450Fma;
7649 break;
7650 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007651 {
7652 libCall = spv::GLSLstd450FrexpStruct;
7653 assert(builder.isPointerType(typeId1));
7654 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007655 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007656 if (width == 16)
7657 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7658 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007659 if (builder.getNumComponents(operands[0]) == 1)
7660 frexpIntType = builder.makeIntegerType(width, true);
7661 else
John Kessenich8985fc92020-03-03 10:25:07 -07007662 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7663 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007664 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7665 consumedOperands = 1;
7666 }
John Kessenich55e7d112015-11-15 21:33:39 -07007667 break;
7668 case glslang::EOpLdexp:
7669 libCall = spv::GLSLstd450Ldexp;
7670 break;
7671
Rex Xu574ab042016-04-14 16:53:07 +08007672 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007673 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007674
John Kessenich66011cb2018-03-06 16:12:04 -07007675 case glslang::EOpSubgroupBroadcast:
7676 case glslang::EOpSubgroupBallotBitExtract:
7677 case glslang::EOpSubgroupShuffle:
7678 case glslang::EOpSubgroupShuffleXor:
7679 case glslang::EOpSubgroupShuffleUp:
7680 case glslang::EOpSubgroupShuffleDown:
7681 case glslang::EOpSubgroupClusteredAdd:
7682 case glslang::EOpSubgroupClusteredMul:
7683 case glslang::EOpSubgroupClusteredMin:
7684 case glslang::EOpSubgroupClusteredMax:
7685 case glslang::EOpSubgroupClusteredAnd:
7686 case glslang::EOpSubgroupClusteredOr:
7687 case glslang::EOpSubgroupClusteredXor:
7688 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007689 case glslang::EOpSubgroupPartitionedAdd:
7690 case glslang::EOpSubgroupPartitionedMul:
7691 case glslang::EOpSubgroupPartitionedMin:
7692 case glslang::EOpSubgroupPartitionedMax:
7693 case glslang::EOpSubgroupPartitionedAnd:
7694 case glslang::EOpSubgroupPartitionedOr:
7695 case glslang::EOpSubgroupPartitionedXor:
7696 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7697 case glslang::EOpSubgroupPartitionedInclusiveMul:
7698 case glslang::EOpSubgroupPartitionedInclusiveMin:
7699 case glslang::EOpSubgroupPartitionedInclusiveMax:
7700 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7701 case glslang::EOpSubgroupPartitionedInclusiveOr:
7702 case glslang::EOpSubgroupPartitionedInclusiveXor:
7703 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7704 case glslang::EOpSubgroupPartitionedExclusiveMul:
7705 case glslang::EOpSubgroupPartitionedExclusiveMin:
7706 case glslang::EOpSubgroupPartitionedExclusiveMax:
7707 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7708 case glslang::EOpSubgroupPartitionedExclusiveOr:
7709 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007710 return createSubgroupOperation(op, typeId, operands, typeProxy);
7711
Rex Xu9d93a232016-05-05 12:30:44 +08007712 case glslang::EOpSwizzleInvocations:
7713 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7714 libCall = spv::SwizzleInvocationsAMD;
7715 break;
7716 case glslang::EOpSwizzleInvocationsMasked:
7717 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7718 libCall = spv::SwizzleInvocationsMaskedAMD;
7719 break;
7720 case glslang::EOpWriteInvocation:
7721 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7722 libCall = spv::WriteInvocationAMD;
7723 break;
7724
7725 case glslang::EOpMin3:
7726 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7727 if (isFloat)
7728 libCall = spv::FMin3AMD;
7729 else {
7730 if (isUnsigned)
7731 libCall = spv::UMin3AMD;
7732 else
7733 libCall = spv::SMin3AMD;
7734 }
7735 break;
7736 case glslang::EOpMax3:
7737 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7738 if (isFloat)
7739 libCall = spv::FMax3AMD;
7740 else {
7741 if (isUnsigned)
7742 libCall = spv::UMax3AMD;
7743 else
7744 libCall = spv::SMax3AMD;
7745 }
7746 break;
7747 case glslang::EOpMid3:
7748 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7749 if (isFloat)
7750 libCall = spv::FMid3AMD;
7751 else {
7752 if (isUnsigned)
7753 libCall = spv::UMid3AMD;
7754 else
7755 libCall = spv::SMid3AMD;
7756 }
7757 break;
7758
7759 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007760 if (typeProxy == glslang::EbtFloat16)
7761 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007762 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7763 libCall = spv::InterpolateAtVertexAMD;
7764 break;
Chao Chen3c366992018-09-19 11:41:59 -07007765
Daniel Kochdb32b242020-03-17 20:42:47 -04007766 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007767 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007768 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007769 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007770 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007771 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007772 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007773 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007774 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007775 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007776
7777 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007778 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7779 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007780 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007781 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7782 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007783 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007784 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7785 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007786 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007787 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7788 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007789 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007790 typeId = builder.makeBoolType();
7791 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007792 break;
7793 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007794 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007795 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007796 break;
7797 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007798 typeId = builder.makeFloatType(32);
7799 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007800 break;
7801 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007802 typeId = builder.makeIntType(32);
7803 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007804 break;
7805 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007806 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007807 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007808 break;
7809 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007810 typeId = builder.makeIntType(32);
7811 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007812 break;
7813 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007814 typeId = builder.makeIntType(32);
7815 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007816 break;
7817 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007818 typeId = builder.makeIntType(32);
7819 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007820 break;
7821 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007822 typeId = builder.makeIntType(32);
7823 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007824 break;
7825 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007826 typeId = builder.makeIntType(32);
7827 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007828 break;
7829 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007830 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7831 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007832 break;
7833 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007834 typeId = builder.makeBoolType();
7835 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007836 break;
7837 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007838 typeId = builder.makeBoolType();
7839 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007840 break;
7841 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007842 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7843 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007844 break;
7845 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007846 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7847 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007848 break;
7849 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007850 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7851 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007852 break;
7853 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007854 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7855 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007856 break;
7857 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007858 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007859 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007860 break;
7861 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007862 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007863 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007864 break;
Chao Chen3c366992018-09-19 11:41:59 -07007865 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7866 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7867 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007868 case glslang::EOpCooperativeMatrixMulAdd:
7869 opCode = spv::OpCooperativeMatrixMulAddNV;
7870 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007871#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007872 default:
7873 return 0;
7874 }
7875
7876 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007877 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007878 // Use an extended instruction from the standard library.
7879 // Construct the call arguments, without modifying the original operands vector.
7880 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7881 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007882 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007883 } else if (opCode == spv::OpDot && !isFloat) {
7884 // int dot(int, int)
7885 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7886 const int componentCount = builder.getNumComponents(operands[0]);
7887 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7888 builder.setPrecision(mulOp, precision);
7889 id = builder.createCompositeExtract(mulOp, typeId, 0);
7890 for (int i = 1; i < componentCount; ++i) {
7891 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007892 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007893 }
John Kessenich2359bd02015-12-06 19:29:11 -07007894 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007895 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007896 case 0:
7897 // should all be handled by visitAggregate and createNoArgOperation
7898 assert(0);
7899 return 0;
7900 case 1:
7901 // should all be handled by createUnaryOperation
7902 assert(0);
7903 return 0;
7904 case 2:
7905 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7906 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007907 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007908 // anything 3 or over doesn't have l-value operands, so all should be consumed
7909 assert(consumedOperands == operands.size());
7910 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007911 break;
7912 }
7913 }
7914
John Kessenichb9197c82019-08-11 07:41:45 -06007915#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007916 // Decode the return types that were structures
7917 switch (op) {
7918 case glslang::EOpAddCarry:
7919 case glslang::EOpSubBorrow:
7920 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7921 id = builder.createCompositeExtract(id, typeId0, 0);
7922 break;
7923 case glslang::EOpUMulExtended:
7924 case glslang::EOpIMulExtended:
7925 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7926 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7927 break;
7928 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007929 {
7930 assert(operands.size() == 2);
7931 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7932 // "exp" is floating-point type (from HLSL intrinsic)
7933 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7934 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7935 builder.createStore(member1, operands[1]);
7936 } else
7937 // "exp" is integer type (from GLSL built-in function)
7938 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7939 id = builder.createCompositeExtract(id, typeId0, 0);
7940 }
John Kessenich55e7d112015-11-15 21:33:39 -07007941 break;
7942 default:
7943 break;
7944 }
John Kessenichb9197c82019-08-11 07:41:45 -06007945#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007946
John Kessenich32cfd492016-02-02 12:37:46 -07007947 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007948}
7949
Rex Xu9d93a232016-05-05 12:30:44 +08007950// Intrinsics with no arguments (or no return value, and no precision).
7951spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007952{
Jeff Bolz36831c92018-09-05 10:11:41 -05007953 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007954 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7955 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007956
7957 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007958 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007959 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007960 if (glslangIntermediate->usingVulkanMemoryModel()) {
7961 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7962 spv::MemorySemanticsOutputMemoryKHRMask |
7963 spv::MemorySemanticsAcquireReleaseMask);
7964 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7965 } else {
7966 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7967 }
John Kessenich82979362017-12-11 04:02:24 -07007968 } else {
7969 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7970 spv::MemorySemanticsWorkgroupMemoryMask |
7971 spv::MemorySemanticsAcquireReleaseMask);
7972 }
John Kessenich140f3df2015-06-26 16:58:36 -06007973 return 0;
7974 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007975 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7976 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007977 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007978 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007979 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7980 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007981 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007982 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007983 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7984 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007985 return 0;
7986 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007987 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7988 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007989 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007990#ifndef GLSLANG_WEB
7991 case glslang::EOpMemoryBarrierAtomicCounter:
7992 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7993 spv::MemorySemanticsAcquireReleaseMask);
7994 return 0;
7995 case glslang::EOpMemoryBarrierImage:
7996 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7997 spv::MemorySemanticsAcquireReleaseMask);
7998 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007999 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008000 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008001 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008002 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008003 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008004 case glslang::EOpDeviceMemoryBarrier:
8005 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8006 spv::MemorySemanticsImageMemoryMask |
8007 spv::MemorySemanticsAcquireReleaseMask);
8008 return 0;
8009 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8010 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8011 spv::MemorySemanticsImageMemoryMask |
8012 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008013 return 0;
8014 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008015 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8016 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008017 return 0;
8018 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008019 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8020 spv::MemorySemanticsWorkgroupMemoryMask |
8021 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008022 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008023 case glslang::EOpSubgroupBarrier:
8024 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8025 spv::MemorySemanticsAcquireReleaseMask);
8026 return spv::NoResult;
8027 case glslang::EOpSubgroupMemoryBarrier:
8028 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8029 spv::MemorySemanticsAcquireReleaseMask);
8030 return spv::NoResult;
8031 case glslang::EOpSubgroupMemoryBarrierBuffer:
8032 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8033 spv::MemorySemanticsAcquireReleaseMask);
8034 return spv::NoResult;
8035 case glslang::EOpSubgroupMemoryBarrierImage:
8036 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8037 spv::MemorySemanticsAcquireReleaseMask);
8038 return spv::NoResult;
8039 case glslang::EOpSubgroupMemoryBarrierShared:
8040 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8041 spv::MemorySemanticsAcquireReleaseMask);
8042 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008043
8044 case glslang::EOpEmitVertex:
8045 builder.createNoResultOp(spv::OpEmitVertex);
8046 return 0;
8047 case glslang::EOpEndPrimitive:
8048 builder.createNoResultOp(spv::OpEndPrimitive);
8049 return 0;
8050
John Kessenich66011cb2018-03-06 16:12:04 -07008051 case glslang::EOpSubgroupElect: {
8052 std::vector<spv::Id> operands;
8053 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8054 }
Rex Xu9d93a232016-05-05 12:30:44 +08008055 case glslang::EOpTime:
8056 {
8057 std::vector<spv::Id> args; // Dummy arguments
8058 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8059 return builder.setPrecision(id, precision);
8060 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008061 case glslang::EOpIgnoreIntersection:
8062 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008063 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008064 case glslang::EOpTerminateRay:
8065 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008066 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008067 case glslang::EOpRayQueryInitialize:
8068 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8069 return 0;
8070 case glslang::EOpRayQueryTerminate:
8071 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8072 return 0;
8073 case glslang::EOpRayQueryGenerateIntersection:
8074 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8075 return 0;
8076 case glslang::EOpRayQueryConfirmIntersection:
8077 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8078 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008079 case glslang::EOpBeginInvocationInterlock:
8080 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8081 return 0;
8082 case glslang::EOpEndInvocationInterlock:
8083 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8084 return 0;
8085
Jeff Bolzba6170b2019-07-01 09:23:23 -05008086 case glslang::EOpIsHelperInvocation:
8087 {
8088 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008089 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8090 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8091 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008092 }
8093
amhagan91fb0092019-07-10 21:14:38 -04008094 case glslang::EOpReadClockSubgroupKHR: {
8095 std::vector<spv::Id> args;
8096 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8097 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8098 builder.addCapability(spv::CapabilityShaderClockKHR);
8099 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8100 }
8101
8102 case glslang::EOpReadClockDeviceKHR: {
8103 std::vector<spv::Id> args;
8104 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8105 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8106 builder.addCapability(spv::CapabilityShaderClockKHR);
8107 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8108 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008109#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008110 default:
John Kessenich155d3512019-08-08 23:29:20 -06008111 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008112 }
John Kessenich155d3512019-08-08 23:29:20 -06008113
8114 logger->missingFunctionality("unknown operation with no arguments");
8115
8116 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008117}
8118
8119spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8120{
John Kessenich2f273362015-07-18 22:34:27 -06008121 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008122 spv::Id id;
8123 if (symbolValues.end() != iter) {
8124 id = iter->second;
8125 return id;
8126 }
8127
8128 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008129 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008130 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008131 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008132 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008133 if (forcedType.second != spv::NoType)
8134 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008135
Rex Xuc884b4a2016-06-29 15:03:44 +08008136 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008137 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8138 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8139 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008140#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008141 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008142 if (symbol->getQualifier().hasComponent())
8143 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8144 if (symbol->getQualifier().hasIndex())
8145 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008146#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008147 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008148 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008149 // atomic counters use this:
8150 if (symbol->getQualifier().hasOffset())
8151 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008152 }
8153
scygan2c864272016-05-18 18:09:17 +02008154 if (symbol->getQualifier().hasLocation())
8155 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008156 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008157 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008158 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008159 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008160 }
John Kessenich140f3df2015-06-26 16:58:36 -06008161 if (symbol->getQualifier().hasSet())
8162 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008163 else if (IsDescriptorResource(symbol->getType())) {
8164 // default to 0
8165 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8166 }
John Kessenich140f3df2015-06-26 16:58:36 -06008167 if (symbol->getQualifier().hasBinding())
8168 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008169 else if (IsDescriptorResource(symbol->getType())) {
8170 // default to 0
8171 builder.addDecoration(id, spv::DecorationBinding, 0);
8172 }
John Kessenich6c292d32016-02-15 20:58:50 -07008173 if (symbol->getQualifier().hasAttachment())
8174 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008175 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008176 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008177 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008178 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008179 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8180 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8181 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8182 }
8183 if (symbol->getQualifier().hasXfbOffset())
8184 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008185 }
8186
John Kessenichb9197c82019-08-11 07:41:45 -06008187 // add built-in variable decoration
8188 if (builtIn != spv::BuiltInMax) {
8189 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8190 }
8191
8192#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008193 if (symbol->getType().isImage()) {
8194 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008195 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8196 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008197 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008198 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008199 }
8200
John Kessenich5611c6d2018-04-05 11:25:02 -06008201 // nonuniform
8202 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8203
chaoc0ad6a4e2016-12-19 16:29:34 -08008204 if (builtIn == spv::BuiltInSampleMask) {
8205 spv::Decoration decoration;
8206 // GL_NV_sample_mask_override_coverage extension
8207 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008208 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008209 else
8210 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008211 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008212 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008213 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008214 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8215 }
8216 }
chaoc771d89f2017-01-13 01:10:53 -08008217 else if (builtIn == spv::BuiltInLayer) {
8218 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008219 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008220 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008221 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8222 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8223 }
John Kessenichb41bff62017-08-11 13:07:17 -06008224 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008225 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8226 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008227 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8228 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8229 }
8230 }
8231
chaoc6e5acae2016-12-20 13:28:52 -08008232 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008233 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008234 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008235 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8236 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008237 if (symbol->getQualifier().pervertexNV) {
8238 builder.addDecoration(id, spv::DecorationPerVertexNV);
8239 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8240 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8241 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008242
John Kessenich5d610ee2018-03-07 18:05:55 -07008243 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8244 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8245 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8246 symbol->getType().getQualifier().semanticName);
8247 }
8248
John Kessenich7015bd62019-08-01 03:28:08 -06008249 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008250 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8251 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008252 }
John Kessenichb9197c82019-08-11 07:41:45 -06008253#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008254
John Kessenich140f3df2015-06-26 16:58:36 -06008255 return id;
8256}
8257
John Kessenicha28f7a72019-08-06 07:00:58 -06008258#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008259// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8260void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8261{
8262 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008263 if (qualifier.perPrimitiveNV) {
8264 // Need to add capability/extension for fragment shader.
8265 // Mesh shader already adds this by default.
8266 if (glslangIntermediate->getStage() == EShLangFragment) {
8267 builder.addCapability(spv::CapabilityMeshShadingNV);
8268 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8269 }
Chao Chen3c366992018-09-19 11:41:59 -07008270 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008271 }
Chao Chen3c366992018-09-19 11:41:59 -07008272 if (qualifier.perViewNV)
8273 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8274 if (qualifier.perTaskNV)
8275 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8276 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008277 if (qualifier.perPrimitiveNV) {
8278 // Need to add capability/extension for fragment shader.
8279 // Mesh shader already adds this by default.
8280 if (glslangIntermediate->getStage() == EShLangFragment) {
8281 builder.addCapability(spv::CapabilityMeshShadingNV);
8282 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8283 }
Chao Chen3c366992018-09-19 11:41:59 -07008284 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008285 }
Chao Chen3c366992018-09-19 11:41:59 -07008286 if (qualifier.perViewNV)
8287 builder.addDecoration(id, spv::DecorationPerViewNV);
8288 if (qualifier.perTaskNV)
8289 builder.addDecoration(id, spv::DecorationPerTaskNV);
8290 }
8291}
8292#endif
8293
John Kessenich55e7d112015-11-15 21:33:39 -07008294// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008295// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008296//
8297// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8298//
8299// Recursively walk the nodes. The nodes form a tree whose leaves are
8300// regular constants, which themselves are trees that createSpvConstant()
8301// recursively walks. So, this function walks the "top" of the tree:
8302// - emit specialization constant-building instructions for specConstant
8303// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008304spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008305{
John Kessenich7cc0e282016-03-20 00:46:02 -06008306 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008307
qining4f4bb812016-04-03 23:55:17 -04008308 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008309 if (! node.getQualifier().specConstant) {
8310 // hand off to the non-spec-constant path
8311 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8312 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008313 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8314 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8315 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008316 }
8317
8318 // We now know we have a specialization constant to build
8319
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008320 // Extra capabilities may be needed.
8321 if (node.getType().contains8BitInt())
8322 builder.addCapability(spv::CapabilityInt8);
8323 if (node.getType().contains16BitFloat())
8324 builder.addCapability(spv::CapabilityFloat16);
8325 if (node.getType().contains16BitInt())
8326 builder.addCapability(spv::CapabilityInt16);
8327 if (node.getType().contains64BitInt())
8328 builder.addCapability(spv::CapabilityInt64);
8329 if (node.getType().containsDouble())
8330 builder.addCapability(spv::CapabilityFloat64);
8331
John Kessenichd94c0032016-05-30 19:29:40 -06008332 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008333 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8334 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8335 std::vector<spv::Id> dimConstId;
8336 for (int dim = 0; dim < 3; ++dim) {
8337 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8338 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008339 if (specConst) {
8340 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8341 glslangIntermediate->getLocalSizeSpecId(dim));
8342 }
qining4f4bb812016-04-03 23:55:17 -04008343 }
8344 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8345 }
8346
8347 // An AST node labelled as specialization constant should be a symbol node.
8348 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8349 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008350 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008351 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008352 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8353 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8354 // will set the builder into spec constant op instruction generating mode.
8355 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008356 result = accessChainLoad(sub_tree->getType());
8357 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008358 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008359 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008360 } else {
8361 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008362 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008363 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008364 builder.addName(result, sn->getName().c_str());
8365 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008366 }
qining4f4bb812016-04-03 23:55:17 -04008367
8368 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8369 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008370 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008371 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008372}
8373
John Kessenich140f3df2015-06-26 16:58:36 -06008374// Use 'consts' as the flattened glslang source of scalar constants to recursively
8375// build the aggregate SPIR-V constant.
8376//
8377// If there are not enough elements present in 'consts', 0 will be substituted;
8378// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8379//
John Kessenich8985fc92020-03-03 10:25:07 -07008380spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8381 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008382{
8383 // vector of constants for SPIR-V
8384 std::vector<spv::Id> spvConsts;
8385
8386 // Type is used for struct and array constants
8387 spv::Id typeId = convertGlslangToSpvType(glslangType);
8388
8389 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008390 glslang::TType elementType(glslangType, 0);
8391 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008392 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008393 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008394 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008395 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008396 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008397 } else if (glslangType.isCoopMat()) {
8398 glslang::TType componentType(glslangType.getBasicType());
8399 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008400 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008401 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8402 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008403 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008404 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008405 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8406 bool zero = nextConst >= consts.size();
8407 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008408 case glslang::EbtInt:
8409 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8410 break;
8411 case glslang::EbtUint:
8412 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8413 break;
8414 case glslang::EbtFloat:
8415 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8416 break;
8417 case glslang::EbtBool:
8418 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8419 break;
8420#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008421 case glslang::EbtInt8:
8422 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8423 break;
8424 case glslang::EbtUint8:
8425 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8426 break;
8427 case glslang::EbtInt16:
8428 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8429 break;
8430 case glslang::EbtUint16:
8431 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8432 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008433 case glslang::EbtInt64:
8434 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8435 break;
8436 case glslang::EbtUint64:
8437 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8438 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008439 case glslang::EbtDouble:
8440 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8441 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008442 case glslang::EbtFloat16:
8443 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8444 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008445#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008446 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008447 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008448 break;
8449 }
8450 ++nextConst;
8451 }
8452 } else {
8453 // we have a non-aggregate (scalar) constant
8454 bool zero = nextConst >= consts.size();
8455 spv::Id scalar = 0;
8456 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008457 case glslang::EbtInt:
8458 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8459 break;
8460 case glslang::EbtUint:
8461 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8462 break;
8463 case glslang::EbtFloat:
8464 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8465 break;
8466 case glslang::EbtBool:
8467 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8468 break;
8469#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008470 case glslang::EbtInt8:
8471 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8472 break;
8473 case glslang::EbtUint8:
8474 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8475 break;
8476 case glslang::EbtInt16:
8477 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8478 break;
8479 case glslang::EbtUint16:
8480 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8481 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008482 case glslang::EbtInt64:
8483 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8484 break;
8485 case glslang::EbtUint64:
8486 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8487 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008488 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008489 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008490 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008491 case glslang::EbtFloat16:
8492 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8493 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008494 case glslang::EbtReference:
8495 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8496 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8497 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008498#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008499 case glslang::EbtString:
8500 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8501 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008502 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008503 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008504 break;
8505 }
8506 ++nextConst;
8507 return scalar;
8508 }
8509
8510 return builder.makeCompositeConstant(typeId, spvConsts);
8511}
8512
John Kessenich7c1aa102015-10-15 13:29:11 -06008513// Return true if the node is a constant or symbol whose reading has no
8514// non-trivial observable cost or effect.
8515bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8516{
8517 // don't know what this is
8518 if (node == nullptr)
8519 return false;
8520
8521 // a constant is safe
8522 if (node->getAsConstantUnion() != nullptr)
8523 return true;
8524
8525 // not a symbol means non-trivial
8526 if (node->getAsSymbolNode() == nullptr)
8527 return false;
8528
8529 // a symbol, depends on what's being read
8530 switch (node->getType().getQualifier().storage) {
8531 case glslang::EvqTemporary:
8532 case glslang::EvqGlobal:
8533 case glslang::EvqIn:
8534 case glslang::EvqInOut:
8535 case glslang::EvqConst:
8536 case glslang::EvqConstReadOnly:
8537 case glslang::EvqUniform:
8538 return true;
8539 default:
8540 return false;
8541 }
qining25262b32016-05-06 17:25:16 -04008542}
John Kessenich7c1aa102015-10-15 13:29:11 -06008543
8544// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008545// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008546// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008547// Return true if trivial.
8548bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8549{
8550 if (node == nullptr)
8551 return false;
8552
John Kessenich84cc15f2017-05-24 16:44:47 -06008553 // count non scalars as trivial, as well as anything coming from HLSL
8554 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008555 return true;
8556
John Kessenich7c1aa102015-10-15 13:29:11 -06008557 // symbols and constants are trivial
8558 if (isTrivialLeaf(node))
8559 return true;
8560
8561 // otherwise, it needs to be a simple operation or one or two leaf nodes
8562
8563 // not a simple operation
8564 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8565 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8566 if (binaryNode == nullptr && unaryNode == nullptr)
8567 return false;
8568
8569 // not on leaf nodes
8570 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8571 return false;
8572
8573 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8574 return false;
8575 }
8576
8577 switch (node->getAsOperator()->getOp()) {
8578 case glslang::EOpLogicalNot:
8579 case glslang::EOpConvIntToBool:
8580 case glslang::EOpConvUintToBool:
8581 case glslang::EOpConvFloatToBool:
8582 case glslang::EOpConvDoubleToBool:
8583 case glslang::EOpEqual:
8584 case glslang::EOpNotEqual:
8585 case glslang::EOpLessThan:
8586 case glslang::EOpGreaterThan:
8587 case glslang::EOpLessThanEqual:
8588 case glslang::EOpGreaterThanEqual:
8589 case glslang::EOpIndexDirect:
8590 case glslang::EOpIndexDirectStruct:
8591 case glslang::EOpLogicalXor:
8592 case glslang::EOpAny:
8593 case glslang::EOpAll:
8594 return true;
8595 default:
8596 return false;
8597 }
8598}
8599
8600// Emit short-circuiting code, where 'right' is never evaluated unless
8601// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008602spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8603 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008604{
8605 spv::Id boolTypeId = builder.makeBoolType();
8606
8607 // emit left operand
8608 builder.clearAccessChain();
8609 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008610 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008611
8612 // Operands to accumulate OpPhi operands
8613 std::vector<spv::Id> phiOperands;
8614 // accumulate left operand's phi information
8615 phiOperands.push_back(leftId);
8616 phiOperands.push_back(builder.getBuildPoint()->getId());
8617
8618 // Make the two kinds of operation symmetric with a "!"
8619 // || => emit "if (! left) result = right"
8620 // && => emit "if ( left) result = right"
8621 //
8622 // TODO: this runtime "not" for || could be avoided by adding functionality
8623 // to 'builder' to have an "else" without an "then"
8624 if (op == glslang::EOpLogicalOr)
8625 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8626
8627 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008628 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008629
8630 // emit right operand as the "then" part of the "if"
8631 builder.clearAccessChain();
8632 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008633 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008634
8635 // accumulate left operand's phi information
8636 phiOperands.push_back(rightId);
8637 phiOperands.push_back(builder.getBuildPoint()->getId());
8638
8639 // finish the "if"
8640 ifBuilder.makeEndIf();
8641
8642 // phi together the two results
8643 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8644}
8645
John Kessenicha28f7a72019-08-06 07:00:58 -06008646#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008647// Return type Id of the imported set of extended instructions corresponds to the name.
8648// Import this set if it has not been imported yet.
8649spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8650{
8651 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8652 return extBuiltinMap[name];
8653 else {
Rex Xu51596642016-09-21 18:56:12 +08008654 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008655 spv::Id extBuiltins = builder.import(name);
8656 extBuiltinMap[name] = extBuiltins;
8657 return extBuiltins;
8658 }
8659}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008660#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008661
John Kessenich140f3df2015-06-26 16:58:36 -06008662}; // end anonymous namespace
8663
8664namespace glslang {
8665
John Kessenich68d78fd2015-07-12 19:28:10 -06008666void GetSpirvVersion(std::string& version)
8667{
John Kessenich9e55f632015-07-15 10:03:39 -06008668 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008669 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008670 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008671 version = buf;
8672}
8673
John Kessenicha372a3e2017-11-02 22:32:14 -06008674// For low-order part of the generator's magic number. Bump up
8675// when there is a change in the style (e.g., if SSA form changes,
8676// or a different instruction sequence to do something gets used).
8677int GetSpirvGeneratorVersion()
8678{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008679 // return 1; // start
8680 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008681 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008682 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008683 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008684 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8685 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008686 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008687 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008688 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8689 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008690}
8691
John Kessenich140f3df2015-06-26 16:58:36 -06008692// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008693void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008694{
8695 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008696 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008697 if (out.fail())
8698 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008699 for (int i = 0; i < (int)spirv.size(); ++i) {
8700 unsigned int word = spirv[i];
8701 out.write((const char*)&word, 4);
8702 }
8703 out.close();
8704}
8705
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008706// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008707void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008708{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008709#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008710 std::ofstream out;
8711 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008712 if (out.fail())
8713 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008714 out << "\t// " <<
8715 GetSpirvGeneratorVersion() <<
8716 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8717 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008718 if (varName != nullptr) {
8719 out << "\t #pragma once" << std::endl;
8720 out << "const uint32_t " << varName << "[] = {" << std::endl;
8721 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008722 const int WORDS_PER_LINE = 8;
8723 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8724 out << "\t";
8725 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8726 const unsigned int word = spirv[i + j];
8727 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8728 if (i + j + 1 < (int)spirv.size()) {
8729 out << ",";
8730 }
8731 }
8732 out << std::endl;
8733 }
Flavio15017db2017-02-15 14:29:33 -08008734 if (varName != nullptr) {
8735 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008736 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008737 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008738 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008739#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008740}
8741
John Kessenich140f3df2015-06-26 16:58:36 -06008742//
8743// Set up the glslang traversal
8744//
John Kessenich4e11b612018-08-30 16:56:59 -06008745void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008746{
Lei Zhang17535f72016-05-04 15:55:59 -04008747 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008748 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008749}
8750
John Kessenich4e11b612018-08-30 16:56:59 -06008751void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008752 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008753{
John Kessenich140f3df2015-06-26 16:58:36 -06008754 TIntermNode* root = intermediate.getTreeRoot();
8755
8756 if (root == 0)
8757 return;
8758
John Kessenich4e11b612018-08-30 16:56:59 -06008759 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008760 if (options == nullptr)
8761 options = &defaultOptions;
8762
John Kessenich4e11b612018-08-30 16:56:59 -06008763 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008764
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008765 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008766 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008767 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008768 it.dumpSpv(spirv);
8769
GregFfb03a552018-03-29 11:49:14 -06008770#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008771 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8772 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008773 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008774 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8775 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008776 prelegalization = false;
8777 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008778 else if (options->stripDebugInfo) {
8779 // Strip debug info even if optimization is disabled.
8780 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8781 }
John Kessenich717c80a2018-08-23 15:17:10 -06008782
John Kessenich4e11b612018-08-30 16:56:59 -06008783 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008784 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008785
John Kessenich717c80a2018-08-23 15:17:10 -06008786 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008787 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008788
GregFcd1f1692017-09-21 18:40:22 -06008789#endif
8790
John Kessenich4e11b612018-08-30 16:56:59 -06008791 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008792}
8793
8794}; // end namespace glslang