blob: 7fc5c1ea30502563e9e9a676ff6c6aa2dcfa0d45 [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
Sidney Just56350ca2020-11-02 11:27:40 -0800717 if (builder.getSpvVersion() < spv::Spv_1_5) {
718 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
719 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
720 }
721 else
722 builder.addCapability(spv::CapabilityShaderViewportIndex);
Rex Xu5e317ff2017-03-16 23:02:39 +0800723 }
John Kessenich92187592016-02-01 13:45:25 -0700724 return spv::BuiltInViewportIndex;
725
John Kessenich5e801132016-02-15 11:09:46 -0700726 case glslang::EbvSampleId:
727 builder.addCapability(spv::CapabilitySampleRateShading);
728 return spv::BuiltInSampleId;
729
730 case glslang::EbvSamplePosition:
731 builder.addCapability(spv::CapabilitySampleRateShading);
732 return spv::BuiltInSamplePosition;
733
734 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700735 return spv::BuiltInSampleMask;
736
John Kessenich78a45572016-07-08 14:05:15 -0600737 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700738 if (glslangIntermediate->getStage() == EShLangMeshNV) {
739 return spv::BuiltInLayer;
740 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600741 builder.addCapability(spv::CapabilityGeometry);
742 if (glslangIntermediate->getStage() == EShLangVertex ||
743 glslangIntermediate->getStage() == EShLangTessControl ||
744 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800745
Sidney Just56350ca2020-11-02 11:27:40 -0800746 if (builder.getSpvVersion() < spv::Spv_1_5) {
747 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
748 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
749 } else
750 builder.addCapability(spv::CapabilityShaderLayer);
Rex Xu5e317ff2017-03-16 23:02:39 +0800751 }
John Kessenich78a45572016-07-08 14:05:15 -0600752 return spv::BuiltInLayer;
753
John Kessenichda581a22015-10-14 14:10:30 -0600754 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600755 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800756 builder.addCapability(spv::CapabilityDrawParameters);
757 return spv::BuiltInBaseVertex;
758
John Kessenichda581a22015-10-14 14:10:30 -0600759 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600760 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800761 builder.addCapability(spv::CapabilityDrawParameters);
762 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200763
John Kessenichda581a22015-10-14 14:10:30 -0600764 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600765 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800766 builder.addCapability(spv::CapabilityDrawParameters);
767 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200768
769 case glslang::EbvPrimitiveId:
770 if (glslangIntermediate->getStage() == EShLangFragment)
771 builder.addCapability(spv::CapabilityGeometry);
772 return spv::BuiltInPrimitiveId;
773
Rex Xu37cdcee2017-06-29 17:46:34 +0800774 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800775 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
776 builder.addCapability(spv::CapabilityStencilExportEXT);
777 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800778
Chowa315b562020-07-02 15:50:36 +0800779 case glslang::EbvShadingRateKHR:
780 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
781 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
782 return spv::BuiltInShadingRateKHR;
783
784 case glslang::EbvPrimitiveShadingRateKHR:
785 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
786 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
787 return spv::BuiltInPrimitiveShadingRateKHR;
788
John Kessenich140f3df2015-06-26 16:58:36 -0600789 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600790 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
791 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
792 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
793 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600794 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800795
Rex Xu574ab042016-04-14 16:53:07 +0800796 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800797 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800798 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
799 return spv::BuiltInSubgroupSize;
800
Rex Xu574ab042016-04-14 16:53:07 +0800801 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800802 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800803 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
804 return spv::BuiltInSubgroupLocalInvocationId;
805
Rex Xu574ab042016-04-14 16:53:07 +0800806 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800807 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
808 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600809 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800810
Rex Xu574ab042016-04-14 16:53:07 +0800811 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800812 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
813 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600814 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800815
Rex Xu574ab042016-04-14 16:53:07 +0800816 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800817 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
818 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600819 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800820
Rex Xu574ab042016-04-14 16:53:07 +0800821 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800822 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
823 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600824 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800825
Rex Xu574ab042016-04-14 16:53:07 +0800826 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800827 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
828 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600829 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800830
John Kessenich66011cb2018-03-06 16:12:04 -0700831 case glslang::EbvNumSubgroups:
832 builder.addCapability(spv::CapabilityGroupNonUniform);
833 return spv::BuiltInNumSubgroups;
834
835 case glslang::EbvSubgroupID:
836 builder.addCapability(spv::CapabilityGroupNonUniform);
837 return spv::BuiltInSubgroupId;
838
839 case glslang::EbvSubgroupSize2:
840 builder.addCapability(spv::CapabilityGroupNonUniform);
841 return spv::BuiltInSubgroupSize;
842
843 case glslang::EbvSubgroupInvocation2:
844 builder.addCapability(spv::CapabilityGroupNonUniform);
845 return spv::BuiltInSubgroupLocalInvocationId;
846
847 case glslang::EbvSubgroupEqMask2:
848 builder.addCapability(spv::CapabilityGroupNonUniform);
849 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
850 return spv::BuiltInSubgroupEqMask;
851
852 case glslang::EbvSubgroupGeMask2:
853 builder.addCapability(spv::CapabilityGroupNonUniform);
854 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
855 return spv::BuiltInSubgroupGeMask;
856
857 case glslang::EbvSubgroupGtMask2:
858 builder.addCapability(spv::CapabilityGroupNonUniform);
859 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
860 return spv::BuiltInSubgroupGtMask;
861
862 case glslang::EbvSubgroupLeMask2:
863 builder.addCapability(spv::CapabilityGroupNonUniform);
864 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
865 return spv::BuiltInSubgroupLeMask;
866
867 case glslang::EbvSubgroupLtMask2:
868 builder.addCapability(spv::CapabilityGroupNonUniform);
869 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
870 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600871
Rex Xu17ff3432016-10-14 17:41:45 +0800872 case glslang::EbvBaryCoordNoPersp:
873 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
874 return spv::BuiltInBaryCoordNoPerspAMD;
875
876 case glslang::EbvBaryCoordNoPerspCentroid:
877 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
878 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
879
880 case glslang::EbvBaryCoordNoPerspSample:
881 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
882 return spv::BuiltInBaryCoordNoPerspSampleAMD;
883
884 case glslang::EbvBaryCoordSmooth:
885 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
886 return spv::BuiltInBaryCoordSmoothAMD;
887
888 case glslang::EbvBaryCoordSmoothCentroid:
889 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
890 return spv::BuiltInBaryCoordSmoothCentroidAMD;
891
892 case glslang::EbvBaryCoordSmoothSample:
893 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
894 return spv::BuiltInBaryCoordSmoothSampleAMD;
895
896 case glslang::EbvBaryCoordPullModel:
897 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
898 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800899
John Kessenich6c8aaac2017-02-27 01:20:51 -0700900 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600901 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700902 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700903 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700904
905 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600906 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700907 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700908 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700909
Daniel Koch5154db52018-11-26 10:01:58 -0500910 case glslang::EbvFragSizeEXT:
911 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
912 builder.addCapability(spv::CapabilityFragmentDensityEXT);
913 return spv::BuiltInFragSizeEXT;
914
915 case glslang::EbvFragInvocationCountEXT:
916 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
917 builder.addCapability(spv::CapabilityFragmentDensityEXT);
918 return spv::BuiltInFragInvocationCountEXT;
919
chaoc771d89f2017-01-13 01:10:53 -0800920 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800921 if (!memberDeclaration) {
922 builder.addExtension(spv::E_SPV_NV_viewport_array2);
923 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
924 }
chaoc771d89f2017-01-13 01:10:53 -0800925 return spv::BuiltInViewportMaskNV;
926 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800927 if (!memberDeclaration) {
928 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
929 builder.addCapability(spv::CapabilityShaderStereoViewNV);
930 }
chaoc771d89f2017-01-13 01:10:53 -0800931 return spv::BuiltInSecondaryPositionNV;
932 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800933 if (!memberDeclaration) {
934 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
935 builder.addCapability(spv::CapabilityShaderStereoViewNV);
936 }
chaoc771d89f2017-01-13 01:10:53 -0800937 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800938 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800939 if (!memberDeclaration) {
940 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
941 builder.addCapability(spv::CapabilityPerViewAttributesNV);
942 }
chaocdf3956c2017-02-14 14:52:34 -0800943 return spv::BuiltInPositionPerViewNV;
944 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800945 if (!memberDeclaration) {
946 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
947 builder.addCapability(spv::CapabilityPerViewAttributesNV);
948 }
chaocdf3956c2017-02-14 14:52:34 -0800949 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700950 case glslang::EbvFragFullyCoveredNV:
951 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
952 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
953 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700954 case glslang::EbvFragmentSizeNV:
955 builder.addExtension(spv::E_SPV_NV_shading_rate);
956 builder.addCapability(spv::CapabilityShadingRateNV);
957 return spv::BuiltInFragmentSizeNV;
958 case glslang::EbvInvocationsPerPixelNV:
959 builder.addExtension(spv::E_SPV_NV_shading_rate);
960 builder.addCapability(spv::CapabilityShadingRateNV);
961 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700962
Daniel Koch593a4e02019-05-27 16:46:31 -0400963 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400964 case glslang::EbvLaunchId:
965 return spv::BuiltInLaunchIdKHR;
966 case glslang::EbvLaunchSize:
967 return spv::BuiltInLaunchSizeKHR;
968 case glslang::EbvWorldRayOrigin:
969 return spv::BuiltInWorldRayOriginKHR;
970 case glslang::EbvWorldRayDirection:
971 return spv::BuiltInWorldRayDirectionKHR;
972 case glslang::EbvObjectRayOrigin:
973 return spv::BuiltInObjectRayOriginKHR;
974 case glslang::EbvObjectRayDirection:
975 return spv::BuiltInObjectRayDirectionKHR;
976 case glslang::EbvRayTmin:
977 return spv::BuiltInRayTminKHR;
978 case glslang::EbvRayTmax:
979 return spv::BuiltInRayTmaxKHR;
980 case glslang::EbvInstanceCustomIndex:
981 return spv::BuiltInInstanceCustomIndexKHR;
982 case glslang::EbvHitT:
983 return spv::BuiltInHitTKHR;
984 case glslang::EbvHitKind:
985 return spv::BuiltInHitKindKHR;
986 case glslang::EbvObjectToWorld:
987 case glslang::EbvObjectToWorld3x4:
988 return spv::BuiltInObjectToWorldKHR;
989 case glslang::EbvWorldToObject:
990 case glslang::EbvWorldToObject3x4:
991 return spv::BuiltInWorldToObjectKHR;
992 case glslang::EbvIncomingRayFlags:
993 return spv::BuiltInIncomingRayFlagsKHR;
994 case glslang::EbvGeometryIndex:
995 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400996
997 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700998 case glslang::EbvBaryCoordNV:
999 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1000 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1001 return spv::BuiltInBaryCoordNV;
1002 case glslang::EbvBaryCoordNoPerspNV:
1003 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1004 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1005 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001006
1007 // mesh shaders
1008 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001009 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001010 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001011 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001012 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001013 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001014 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001015 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001016 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001017 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001018 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001019 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001020 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001021 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001022 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001023 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001024
1025 // sm builtins
1026 case glslang::EbvWarpsPerSM:
1027 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1028 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1029 return spv::BuiltInWarpsPerSMNV;
1030 case glslang::EbvSMCount:
1031 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1032 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1033 return spv::BuiltInSMCountNV;
1034 case glslang::EbvWarpID:
1035 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1036 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1037 return spv::BuiltInWarpIDNV;
1038 case glslang::EbvSMID:
1039 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1040 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1041 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001042#endif
1043
Rex Xu3e783f92017-02-22 16:44:48 +08001044 default:
1045 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001046 }
1047}
1048
Rex Xufc618912015-09-09 16:42:49 +08001049// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001050spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001051{
1052 assert(type.getBasicType() == glslang::EbtSampler);
1053
John Kessenichb9197c82019-08-11 07:41:45 -06001054#ifdef GLSLANG_WEB
1055 return spv::ImageFormatUnknown;
1056#endif
1057
John Kessenich5d0fa972016-02-15 11:57:00 -07001058 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001059 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001060 case glslang::ElfRg32f:
1061 case glslang::ElfRg16f:
1062 case glslang::ElfR11fG11fB10f:
1063 case glslang::ElfR16f:
1064 case glslang::ElfRgba16:
1065 case glslang::ElfRgb10A2:
1066 case glslang::ElfRg16:
1067 case glslang::ElfRg8:
1068 case glslang::ElfR16:
1069 case glslang::ElfR8:
1070 case glslang::ElfRgba16Snorm:
1071 case glslang::ElfRg16Snorm:
1072 case glslang::ElfRg8Snorm:
1073 case glslang::ElfR16Snorm:
1074 case glslang::ElfR8Snorm:
1075
1076 case glslang::ElfRg32i:
1077 case glslang::ElfRg16i:
1078 case glslang::ElfRg8i:
1079 case glslang::ElfR16i:
1080 case glslang::ElfR8i:
1081
1082 case glslang::ElfRgb10a2ui:
1083 case glslang::ElfRg32ui:
1084 case glslang::ElfRg16ui:
1085 case glslang::ElfRg8ui:
1086 case glslang::ElfR16ui:
1087 case glslang::ElfR8ui:
1088 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1089 break;
1090
1091 default:
1092 break;
1093 }
1094
1095 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001096 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001097 case glslang::ElfNone: return spv::ImageFormatUnknown;
1098 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1099 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1100 case glslang::ElfR32f: return spv::ImageFormatR32f;
1101 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1102 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1103 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1104 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1105 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1106 case glslang::ElfR16f: return spv::ImageFormatR16f;
1107 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1108 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1109 case glslang::ElfRg16: return spv::ImageFormatRg16;
1110 case glslang::ElfRg8: return spv::ImageFormatRg8;
1111 case glslang::ElfR16: return spv::ImageFormatR16;
1112 case glslang::ElfR8: return spv::ImageFormatR8;
1113 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1114 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1115 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1116 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1117 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1118 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1119 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1120 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1121 case glslang::ElfR32i: return spv::ImageFormatR32i;
1122 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1123 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1124 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1125 case glslang::ElfR16i: return spv::ImageFormatR16i;
1126 case glslang::ElfR8i: return spv::ImageFormatR8i;
1127 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1128 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1129 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1130 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1131 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1132 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1133 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1134 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1135 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1136 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001137 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001138 }
1139}
1140
John Kessenich8985fc92020-03-03 10:25:07 -07001141spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1142 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001143{
John Kesseniche18fd202018-01-30 11:01:39 -07001144 if (selectionNode.getFlatten())
1145 return spv::SelectionControlFlattenMask;
1146 if (selectionNode.getDontFlatten())
1147 return spv::SelectionControlDontFlattenMask;
1148 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001149}
1150
John Kessenich8985fc92020-03-03 10:25:07 -07001151spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1152 const
steve-lunargf1709e72017-05-02 20:14:50 -06001153{
John Kesseniche18fd202018-01-30 11:01:39 -07001154 if (switchNode.getFlatten())
1155 return spv::SelectionControlFlattenMask;
1156 if (switchNode.getDontFlatten())
1157 return spv::SelectionControlDontFlattenMask;
1158 return spv::SelectionControlMaskNone;
1159}
1160
John Kessenicha2858d92018-01-31 08:11:18 -07001161// return a non-0 dependency if the dependency argument must be set
1162spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001163 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001164{
1165 spv::LoopControlMask control = spv::LoopControlMaskNone;
1166
1167 if (loopNode.getDontUnroll())
1168 control = control | spv::LoopControlDontUnrollMask;
1169 if (loopNode.getUnroll())
1170 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001171 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001172 control = control | spv::LoopControlDependencyInfiniteMask;
1173 else if (loopNode.getLoopDependency() > 0) {
1174 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001175 operands.push_back((unsigned int)loopNode.getLoopDependency());
1176 }
1177 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1178 if (loopNode.getMinIterations() > 0) {
1179 control = control | spv::LoopControlMinIterationsMask;
1180 operands.push_back(loopNode.getMinIterations());
1181 }
1182 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1183 control = control | spv::LoopControlMaxIterationsMask;
1184 operands.push_back(loopNode.getMaxIterations());
1185 }
1186 if (loopNode.getIterationMultiple() > 1) {
1187 control = control | spv::LoopControlIterationMultipleMask;
1188 operands.push_back(loopNode.getIterationMultiple());
1189 }
1190 if (loopNode.getPeelCount() > 0) {
1191 control = control | spv::LoopControlPeelCountMask;
1192 operands.push_back(loopNode.getPeelCount());
1193 }
1194 if (loopNode.getPartialCount() > 0) {
1195 control = control | spv::LoopControlPartialCountMask;
1196 operands.push_back(loopNode.getPartialCount());
1197 }
John Kessenicha2858d92018-01-31 08:11:18 -07001198 }
John Kesseniche18fd202018-01-30 11:01:39 -07001199
1200 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001201}
1202
John Kessenicha5c5fb62017-05-05 05:09:58 -06001203// Translate glslang type to SPIR-V storage class.
1204spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1205{
Torosdagli06c2eee2020-03-19 11:09:57 -04001206 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001207 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001208 if (type.getQualifier().isPipeInput())
1209 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001210 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001211 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001212
1213 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001214 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001215 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001216 return spv::StorageClassAtomicCounter;
1217 if (type.containsOpaque())
1218 return spv::StorageClassUniformConstant;
1219 }
1220
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001221 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001222 type.getQualifier().isShaderRecord()) {
1223 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001224 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001225
John Kessenichbed4e4f2017-09-08 02:38:07 -06001226 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001227 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001228 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001229 }
1230
1231 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001232 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001233 return spv::StorageClassPushConstant;
1234 if (type.getBasicType() == glslang::EbtBlock)
1235 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001236 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001237 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001238
1239 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001240 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1241 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1242 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001243 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001244#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001245 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1246 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1247 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1248 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1249 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001250#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001251 default:
1252 assert(0);
1253 break;
1254 }
1255
1256 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001257}
1258
John Kessenich5611c6d2018-04-05 11:25:02 -06001259// Add capabilities pertaining to how an array is indexed.
1260void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1261 const glslang::TType& indexType)
1262{
John Kessenichb9197c82019-08-11 07:41:45 -06001263#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001264 if (indexType.getQualifier().isNonUniform()) {
1265 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001266 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001267 if (baseType.getBasicType() == glslang::EbtSampler) {
1268 if (baseType.getQualifier().hasAttachment())
1269 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001270 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001271 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001272 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001273 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1274 else if (baseType.isImage())
1275 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1276 else if (baseType.isTexture())
1277 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1278 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1279 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1280 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1281 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1282 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1283 }
1284 } else {
1285 // assume a dynamically uniform index
1286 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001287 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001288 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001289 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001290 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001291 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001292 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001293 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001294 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001295 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001296 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001297 }
1298 }
John Kessenichb9197c82019-08-11 07:41:45 -06001299#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001300}
1301
qining25262b32016-05-06 17:25:16 -04001302// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001303// descriptor set.
1304bool IsDescriptorResource(const glslang::TType& type)
1305{
John Kessenichf7497e22016-03-08 21:36:22 -07001306 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001307 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001308 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001309 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001310 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001311
1312 // non block...
1313 // basically samplerXXX/subpass/sampler/texture are all included
1314 // if they are the global-scope-class, not the function parameter
1315 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001316 if (type.getBasicType() == glslang::EbtSampler ||
1317 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001318 return type.getQualifier().isUniformOrBuffer();
1319
1320 // None of the above.
1321 return false;
1322}
1323
John Kesseniche0b6cad2015-12-24 10:30:13 -07001324void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1325{
1326 if (child.layoutMatrix == glslang::ElmNone)
1327 child.layoutMatrix = parent.layoutMatrix;
1328
1329 if (parent.invariant)
1330 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001331 if (parent.flat)
1332 child.flat = true;
1333 if (parent.centroid)
1334 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001335#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001336 if (parent.nopersp)
1337 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001338 if (parent.explicitInterp)
1339 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001340 if (parent.perPrimitiveNV)
1341 child.perPrimitiveNV = true;
1342 if (parent.perViewNV)
1343 child.perViewNV = true;
1344 if (parent.perTaskNV)
1345 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001346 if (parent.patch)
1347 child.patch = true;
1348 if (parent.sample)
1349 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001350 if (parent.coherent)
1351 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001352 if (parent.devicecoherent)
1353 child.devicecoherent = true;
1354 if (parent.queuefamilycoherent)
1355 child.queuefamilycoherent = true;
1356 if (parent.workgroupcoherent)
1357 child.workgroupcoherent = true;
1358 if (parent.subgroupcoherent)
1359 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001360 if (parent.shadercallcoherent)
1361 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001362 if (parent.nonprivate)
1363 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001364 if (parent.volatil)
1365 child.volatil = true;
1366 if (parent.restrict)
1367 child.restrict = true;
1368 if (parent.readonly)
1369 child.readonly = true;
1370 if (parent.writeonly)
1371 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001372#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001373}
1374
John Kessenichf2b7f332016-09-01 17:05:23 -06001375bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001376{
John Kessenich7b9fa252016-01-21 18:56:57 -07001377 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001378 // - struct members might inherit from a struct declaration
1379 // (note that non-block structs don't explicitly inherit,
1380 // only implicitly, meaning no decoration involved)
1381 // - affect decorations on the struct members
1382 // (note smooth does not, and expecting something like volatile
1383 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001384 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001385 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001386}
1387
John Kessenich140f3df2015-06-26 16:58:36 -06001388//
1389// Implement the TGlslangToSpvTraverser class.
1390//
1391
John Kessenich8985fc92020-03-03 10:25:07 -07001392TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1393 const glslang::TIntermediate* glslangIntermediate,
1394 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1395 TIntermTraverser(true, false, true),
1396 options(options),
1397 shaderEntry(nullptr), currentFunction(nullptr),
1398 sequenceDepth(0), logger(buildLogger),
1399 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1400 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1401 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001402 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1403 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001404{
1405 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1406
1407 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001408 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1409 glslangIntermediate->getVersion());
1410
John Kessenich121853f2017-05-31 17:11:16 -06001411 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001412 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001413 builder.setSourceFile(glslangIntermediate->getSourceFile());
1414
1415 // Set the source shader's text. If for SPV version 1.0, include
1416 // a preamble in comments stating the OpModuleProcessed instructions.
1417 // Otherwise, emit those as actual instructions.
1418 std::string text;
1419 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1420 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001421 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001422 text.append("// OpModuleProcessed ");
1423 text.append(processes[p]);
1424 text.append("\n");
1425 } else
1426 builder.addModuleProcessed(processes[p]);
1427 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001428 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001429 text.append("#line 1\n");
1430 text.append(glslangIntermediate->getSourceText());
1431 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001432 // Pass name and text for all included files
1433 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1434 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1435 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001436 }
John Kessenich140f3df2015-06-26 16:58:36 -06001437 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001438
1439 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1440 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1441
1442 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1443 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001444 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001445 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001446 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001447 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001448 memoryModel = spv::MemoryModelVulkanKHR;
1449 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001450 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001451 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001452 builder.setMemoryModel(addressingModel, memoryModel);
1453
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001454 if (glslangIntermediate->usingVariablePointers()) {
1455 builder.addCapability(spv::CapabilityVariablePointers);
1456 }
1457
John Kessenicheee9d532016-09-19 18:09:30 -06001458 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1459 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001460
1461 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001462 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1463 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001464 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001465
1466 // Add the top-level modes for this shader.
1467
John Kessenich92187592016-02-01 13:45:25 -07001468 if (glslangIntermediate->getXfbMode()) {
1469 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001471 }
John Kessenich140f3df2015-06-26 16:58:36 -06001472
alelenv59216d52020-05-21 04:38:41 -07001473 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001474 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1475 }
1476
John Kessenich140f3df2015-06-26 16:58:36 -06001477 unsigned int mode;
1478 switch (glslangIntermediate->getStage()) {
1479 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001480 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001481 break;
1482
John Kessenicha28f7a72019-08-06 07:00:58 -06001483 case EShLangFragment:
1484 builder.addCapability(spv::CapabilityShader);
1485 if (glslangIntermediate->getPixelCenterInteger())
1486 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1487
1488 if (glslangIntermediate->getOriginUpperLeft())
1489 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1490 else
1491 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1492
1493 if (glslangIntermediate->getEarlyFragmentTests())
1494 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1495
1496 if (glslangIntermediate->getPostDepthCoverage()) {
1497 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1498 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1499 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1500 }
1501
John Kessenichb9197c82019-08-11 07:41:45 -06001502 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1503 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1504
1505#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001506
John Kessenicha28f7a72019-08-06 07:00:58 -06001507 switch(glslangIntermediate->getDepth()) {
1508 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1509 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1510 default: mode = spv::ExecutionModeMax; break;
1511 }
1512 if (mode != spv::ExecutionModeMax)
1513 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001514 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001515 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1516 break;
1517 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1518 break;
1519 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1520 break;
1521 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1522 break;
1523 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1524 break;
1525 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1526 break;
1527 default: mode = spv::ExecutionModeMax;
1528 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001529 }
1530 if (mode != spv::ExecutionModeMax) {
1531 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1532 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1533 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1534 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1535 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1536 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1537 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1538 } else {
1539 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1540 }
1541 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1542 }
John Kessenichb9197c82019-08-11 07:41:45 -06001543#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001544 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001545
John Kessenicha28f7a72019-08-06 07:00:58 -06001546 case EShLangCompute:
1547 builder.addCapability(spv::CapabilityShader);
1548 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1549 glslangIntermediate->getLocalSize(1),
1550 glslangIntermediate->getLocalSize(2));
1551 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1552 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1553 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1554 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1555 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1556 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1557 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1558 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1559 }
1560 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001561#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001562 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001563 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001564 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001565
steve-lunarge7412492017-03-23 11:56:07 -06001566 glslang::TLayoutGeometry primitive;
1567
1568 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001569 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1570 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001571 primitive = glslangIntermediate->getOutputPrimitive();
1572 } else {
1573 primitive = glslangIntermediate->getInputPrimitive();
1574 }
1575
1576 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001577 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1578 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1579 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001580 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001581 }
John Kessenich4016e382016-07-15 11:53:56 -06001582 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001583 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1584
John Kesseniche6903322015-10-13 16:29:02 -06001585 switch (glslangIntermediate->getVertexSpacing()) {
1586 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1587 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1588 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001589 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001590 }
John Kessenich4016e382016-07-15 11:53:56 -06001591 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001592 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1593
1594 switch (glslangIntermediate->getVertexOrder()) {
1595 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1596 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001597 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001598 }
John Kessenich4016e382016-07-15 11:53:56 -06001599 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001600 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1601
1602 if (glslangIntermediate->getPointMode())
1603 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001604 break;
1605
1606 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001607 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001608 switch (glslangIntermediate->getInputPrimitive()) {
1609 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1610 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1611 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001612 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001613 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001614 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001615 }
John Kessenich4016e382016-07-15 11:53:56 -06001616 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001617 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001618
John Kessenich140f3df2015-06-26 16:58:36 -06001619 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1620
1621 switch (glslangIntermediate->getOutputPrimitive()) {
1622 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1623 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1624 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001625 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001626 }
John Kessenich4016e382016-07-15 11:53:56 -06001627 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001628 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1629 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1630 break;
1631
Daniel Kochdb32b242020-03-17 20:42:47 -04001632 case EShLangRayGen:
1633 case EShLangIntersect:
1634 case EShLangAnyHit:
1635 case EShLangClosestHit:
1636 case EShLangMiss:
1637 case EShLangCallable:
1638 {
1639 auto& extensions = glslangIntermediate->getRequestedExtensions();
1640 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1641 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1642 builder.addExtension("SPV_KHR_ray_tracing");
1643 }
1644 else {
1645 builder.addCapability(spv::CapabilityRayTracingNV);
1646 builder.addExtension("SPV_NV_ray_tracing");
1647 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001648 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001649 }
Chao Chen3c366992018-09-19 11:41:59 -07001650 case EShLangTaskNV:
1651 case EShLangMeshNV:
1652 builder.addCapability(spv::CapabilityMeshShadingNV);
1653 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1654 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1655 glslangIntermediate->getLocalSize(1),
1656 glslangIntermediate->getLocalSize(2));
1657 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001658 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1659 glslangIntermediate->getVertices());
1660 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1661 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001662
1663 switch (glslangIntermediate->getOutputPrimitive()) {
1664 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1665 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1666 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1667 default: mode = spv::ExecutionModeMax; break;
1668 }
1669 if (mode != spv::ExecutionModeMax)
1670 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1671 }
1672 break;
1673#endif
1674
John Kessenich140f3df2015-06-26 16:58:36 -06001675 default:
1676 break;
1677 }
John Kessenich140f3df2015-06-26 16:58:36 -06001678}
1679
John Kessenichfca82622016-11-26 13:23:20 -07001680// Finish creating SPV, after the traversal is complete.
1681void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001682{
John Kessenichf04c51b2018-08-03 15:56:12 -06001683 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001684 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001685 builder.setBuildPoint(shaderEntry->getLastBlock());
1686 builder.leaveFunction();
1687 }
1688
John Kessenich7ba63412015-12-20 17:37:07 -07001689 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001690 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1691 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001692
David Neto8c3d5b42019-10-21 14:50:31 -04001693 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001694 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001695 // Note: WebGPU code generation must have the opportunity to aggressively
1696 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001697 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001698}
1699
John Kessenichfca82622016-11-26 13:23:20 -07001700// Write the SPV into 'out'.
1701void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001702{
John Kessenichfca82622016-11-26 13:23:20 -07001703 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001704}
1705
1706//
1707// Implement the traversal functions.
1708//
1709// Return true from interior nodes to have the external traversal
1710// continue on to children. Return false if children were
1711// already processed.
1712//
1713
1714//
qining25262b32016-05-06 17:25:16 -04001715// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001716// - uniform/input reads
1717// - output writes
1718// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1719// - something simple that degenerates into the last bullet
1720//
1721void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1722{
qining75d1d802016-04-06 14:42:01 -04001723 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001724 if (symbol->getType().isStruct())
1725 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1726
qining75d1d802016-04-06 14:42:01 -04001727 if (symbol->getType().getQualifier().isSpecConstant())
1728 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1729
Rex Xuf6e0fe82020-10-23 22:54:35 +08001730#ifdef ENABLE_HLSL
1731 // Skip symbol handling if it is string-typed
1732 if (symbol->getBasicType() == glslang::EbtString)
1733 return;
1734#endif
1735
John Kessenich140f3df2015-06-26 16:58:36 -06001736 // getSymbolId() will set up all the IO decorations on the first call.
1737 // Formal function parameters were mapped during makeFunctions().
1738 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001739
John Kessenich7ba63412015-12-20 17:37:07 -07001740 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001741 if (!symbol->getType().getQualifier().isParamInput() &&
1742 !symbol->getType().getQualifier().isParamOutput()) {
1743 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1744 // Consider adding to the OpEntryPoint interface list.
1745 // Only looking at structures if they have at least one member.
1746 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1747 spv::StorageClass sc = builder.getStorageClass(id);
1748 // Before SPIR-V 1.4, we only want to include Input and Output.
1749 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001750 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001751 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1752 iOSet.insert(id);
1753 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001754 }
John Kessenich5f77d862017-09-19 11:09:59 -06001755 }
John Kessenich9c14f772019-06-17 08:38:35 -06001756
Daniel Kochdb32b242020-03-17 20:42:47 -04001757 // If the SPIR-V type is required to be different than the AST type
1758 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001759 // translate now from the SPIR-V type to the AST type, for the consuming
1760 // operation.
1761 // Note this turns it from an l-value to an r-value.
1762 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1763 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1764 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001765 }
1766
1767 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001768 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001769 // Prepare to generate code for the access
1770
1771 // L-value chains will be computed left to right. We're on the symbol now,
1772 // which is the left-most part of the access chain, so now is "clear" time,
1773 // followed by setting the base.
1774 builder.clearAccessChain();
1775
1776 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001777 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001778 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001779 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001780 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001781 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001782 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001783 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001784 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1785 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001786 builder.setAccessChainRValue(id);
1787 else
1788 builder.setAccessChainLValue(id);
1789 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001790
John Kessenichb9197c82019-08-11 07:41:45 -06001791#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001792 // Process linkage-only nodes for any special additional interface work.
1793 if (linkageOnly) {
1794 if (glslangIntermediate->getHlslFunctionality1()) {
1795 // Map implicit counter buffers to their originating buffers, which should have been
1796 // seen by now, given earlier pruning of unused counters, and preservation of order
1797 // of declaration.
1798 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1799 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1800 // Save possible originating buffers for counter buffers, keyed by
1801 // making the potential counter-buffer name.
1802 std::string keyName = symbol->getName().c_str();
1803 keyName = glslangIntermediate->addCounterBufferName(keyName);
1804 counterOriginator[keyName] = symbol;
1805 } else {
1806 // Handle a counter buffer, by finding the saved originating buffer.
1807 std::string keyName = symbol->getName().c_str();
1808 auto it = counterOriginator.find(keyName);
1809 if (it != counterOriginator.end()) {
1810 id = getSymbolId(it->second);
1811 if (id != spv::NoResult) {
1812 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001813 if (counterId != spv::NoResult) {
1814 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001815 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001816 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001817 }
1818 }
1819 }
1820 }
1821 }
1822 }
John Kessenich155d3512019-08-08 23:29:20 -06001823#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001824}
1825
1826bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1827{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001828 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001829 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1830 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1831 }
1832 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1833 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1834 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001835
qining40887662016-04-03 22:20:42 -04001836 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1837 if (node->getType().getQualifier().isSpecConstant())
1838 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1839
John Kessenich140f3df2015-06-26 16:58:36 -06001840 // First, handle special cases
1841 switch (node->getOp()) {
1842 case glslang::EOpAssign:
1843 case glslang::EOpAddAssign:
1844 case glslang::EOpSubAssign:
1845 case glslang::EOpMulAssign:
1846 case glslang::EOpVectorTimesMatrixAssign:
1847 case glslang::EOpVectorTimesScalarAssign:
1848 case glslang::EOpMatrixTimesScalarAssign:
1849 case glslang::EOpMatrixTimesMatrixAssign:
1850 case glslang::EOpDivAssign:
1851 case glslang::EOpModAssign:
1852 case glslang::EOpAndAssign:
1853 case glslang::EOpInclusiveOrAssign:
1854 case glslang::EOpExclusiveOrAssign:
1855 case glslang::EOpLeftShiftAssign:
1856 case glslang::EOpRightShiftAssign:
1857 // A bin-op assign "a += b" means the same thing as "a = a + b"
1858 // where a is evaluated before b. For a simple assignment, GLSL
1859 // says to evaluate the left before the right. So, always, left
1860 // node then right node.
1861 {
1862 // get the left l-value, save it away
1863 builder.clearAccessChain();
1864 node->getLeft()->traverse(this);
1865 spv::Builder::AccessChain lValue = builder.getAccessChain();
1866
1867 // evaluate the right
1868 builder.clearAccessChain();
1869 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001870 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001871
1872 if (node->getOp() != glslang::EOpAssign) {
1873 // the left is also an r-value
1874 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001875 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001876
1877 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001878 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001879 TranslateNoContractionDecoration(node->getType().getQualifier()),
1880 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001881 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001882 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1883 node->getType().getBasicType());
1884
1885 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001886 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001887 }
1888
1889 // store the result
1890 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001891 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001892
1893 // assignments are expressions having an rValue after they are evaluated...
1894 builder.clearAccessChain();
1895 builder.setAccessChainRValue(rValue);
1896 }
1897 return false;
1898 case glslang::EOpIndexDirect:
1899 case glslang::EOpIndexDirectStruct:
1900 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001901 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001902 // Get the left part of the access chain.
1903 node->getLeft()->traverse(this);
1904
1905 // Add the next element in the chain
1906
David Netoa901ffe2016-06-08 14:11:40 +01001907 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001908 if (! node->getLeft()->getType().isArray() &&
1909 node->getLeft()->getType().isVector() &&
1910 node->getOp() == glslang::EOpIndexDirect) {
1911 // This is essentially a hard-coded vector swizzle of size 1,
1912 // so short circuit the access-chain stuff with a swizzle.
1913 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001914 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001915 int dummySize;
1916 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1917 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001918 glslangIntermediate->getBaseAlignmentScalar(
1919 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001920 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001921
1922 // Load through a block reference is performed with a dot operator that
1923 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1924 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001925 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001926 !node->getLeft()->getType().isArray() &&
1927 node->getOp() == glslang::EOpIndexDirectStruct)
1928 {
1929 spv::Id left = accessChainLoad(node->getLeft()->getType());
1930 builder.clearAccessChain();
1931 builder.setAccessChainLValue(left);
1932 }
1933
David Netoa901ffe2016-06-08 14:11:40 +01001934 int spvIndex = glslangIndex;
1935 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1936 node->getOp() == glslang::EOpIndexDirectStruct)
1937 {
1938 // This may be, e.g., an anonymous block-member selection, which generally need
1939 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001940 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1941 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1942 std::vector<int>& remapper = memberRemapper[glslangId];
1943 assert(remapper.size() > 0);
1944 spvIndex = remapper[glslangIndex];
1945 }
David Netoa901ffe2016-06-08 14:11:40 +01001946 }
John Kessenichebb50532016-05-16 19:22:05 -06001947
David Netoa901ffe2016-06-08 14:11:40 +01001948 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001949 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1950 TranslateCoherent(node->getLeft()->getType()),
1951 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001952
1953 // Add capabilities here for accessing PointSize and clip/cull distance.
1954 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001955 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001956 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001957 }
1958 }
1959 return false;
1960 case glslang::EOpIndexIndirect:
1961 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001962 // Array, matrix, or vector indirection with variable index.
1963 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001964 // matrices are arrays of vectors, so will also work for a matrix.
1965 // Will use the access chain's 'component' for variable index into a vector.
1966
1967 // This adapter is building access chains left to right.
1968 // Set up the access chain to the left.
1969 node->getLeft()->traverse(this);
1970
1971 // save it so that computing the right side doesn't trash it
1972 spv::Builder::AccessChain partial = builder.getAccessChain();
1973
1974 // compute the next index in the chain
1975 builder.clearAccessChain();
1976 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001977 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001978
John Kessenich5611c6d2018-04-05 11:25:02 -06001979 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1980
John Kessenich140f3df2015-06-26 16:58:36 -06001981 // restore the saved access chain
1982 builder.setAccessChain(partial);
1983
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001984 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1985 int dummySize;
1986 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1987 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001988 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1989 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001990 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001991 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1992 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001993 }
1994 return false;
1995 case glslang::EOpVectorSwizzle:
1996 {
1997 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001998 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001999 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002000 int dummySize;
2001 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
2002 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07002003 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2004 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06002005 }
2006 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07002007 case glslang::EOpMatrixSwizzle:
2008 logger->missingFunctionality("matrix swizzle");
2009 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06002010 case glslang::EOpLogicalOr:
2011 case glslang::EOpLogicalAnd:
2012 {
2013
2014 // These may require short circuiting, but can sometimes be done as straight
2015 // binary operations. The right operand must be short circuited if it has
2016 // side effects, and should probably be if it is complex.
2017 if (isTrivial(node->getRight()->getAsTyped()))
2018 break; // handle below as a normal binary operation
2019 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07002020 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
2021 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06002022 builder.clearAccessChain();
2023 builder.setAccessChainRValue(result);
2024 }
2025 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002026 default:
2027 break;
2028 }
2029
2030 // Assume generic binary op...
2031
John Kessenich32cfd492016-02-02 12:37:46 -07002032 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002033 builder.clearAccessChain();
2034 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002035 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002036
John Kessenich32cfd492016-02-02 12:37:46 -07002037 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002038 builder.clearAccessChain();
2039 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002040 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002041
John Kessenich32cfd492016-02-02 12:37:46 -07002042 // get result
John Kessenichead86222018-03-28 18:01:20 -06002043 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002044 TranslateNoContractionDecoration(node->getType().getQualifier()),
2045 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002046 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002047 convertGlslangToSpvType(node->getType()), left, right,
2048 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002049
John Kessenich50e57562015-12-21 21:21:11 -07002050 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002051 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002052 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002053 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002054 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002055 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002056 return false;
2057 }
John Kessenich140f3df2015-06-26 16:58:36 -06002058}
2059
John Kessenich9c14f772019-06-17 08:38:35 -06002060// Figure out what, if any, type changes are needed when accessing a specific built-in.
2061// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2062// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002063std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002064 const glslang::TType& glslangType)
2065{
Daniel Kochdb32b242020-03-17 20:42:47 -04002066 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002067 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002068 case glslang::EbvSubGroupEqMask:
2069 case glslang::EbvSubGroupGeMask:
2070 case glslang::EbvSubGroupGtMask:
2071 case glslang::EbvSubGroupLeMask:
2072 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002073 // these require changing a 64-bit scaler -> a vector of 32-bit components
2074 if (glslangType.isVector())
2075 break;
2076 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2077 builder.makeUintType(64));
2078 return ret;
2079 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002080 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2081 // builtins. During visitBinary we insert a transpose
2082 case glslang::EbvWorldToObject3x4:
2083 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002084 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2085 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2086 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002087 return ret;
2088 }
John Kessenich9c14f772019-06-17 08:38:35 -06002089 default:
2090 break;
2091 }
2092
2093 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2094 return ret;
2095}
2096
2097// For an object previously identified (see getForcedType() and forceType)
2098// as needing type translations, do the translation needed for a load, turning
2099// an L-value into in R-value.
2100spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2101{
2102 const auto forceIt = forceType.find(object);
2103 if (forceIt == forceType.end())
2104 return object;
2105
2106 spv::Id desiredTypeId = forceIt->second;
2107 spv::Id objectTypeId = builder.getTypeId(object);
2108 assert(builder.isPointerType(objectTypeId));
2109 objectTypeId = builder.getContainedTypeId(objectTypeId);
2110 if (builder.isVectorType(objectTypeId) &&
2111 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2112 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2113 // handle 32-bit v.xy* -> 64-bit
2114 builder.clearAccessChain();
2115 builder.setAccessChainLValue(object);
2116 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2117 std::vector<spv::Id> components;
2118 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2119 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2120
2121 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2122 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2123 builder.createCompositeConstruct(vecType, components));
2124 } else {
2125 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2126 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002127 } else if (builder.isMatrixType(objectTypeId)) {
2128 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2129 // and we insert a transpose after loading the original non-transposed builtins
2130 builder.clearAccessChain();
2131 builder.setAccessChainLValue(object);
2132 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2133 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2134
2135 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002136 logger->missingFunctionality("forcing non 32-bit vector type");
2137 }
2138
2139 return object;
2140}
2141
John Kessenich140f3df2015-06-26 16:58:36 -06002142bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2143{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002144 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002145
qining40887662016-04-03 22:20:42 -04002146 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2147 if (node->getType().getQualifier().isSpecConstant())
2148 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2149
John Kessenichfc51d282015-08-19 13:34:18 -06002150 spv::Id result = spv::NoResult;
2151
2152 // try texturing first
2153 result = createImageTextureFunctionCall(node);
2154 if (result != spv::NoResult) {
2155 builder.clearAccessChain();
2156 builder.setAccessChainRValue(result);
2157
2158 return false; // done with this node
2159 }
2160
2161 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002162
2163 if (node->getOp() == glslang::EOpArrayLength) {
2164 // Quite special; won't want to evaluate the operand.
2165
John Kessenich5611c6d2018-04-05 11:25:02 -06002166 // Currently, the front-end does not allow .length() on an array until it is sized,
2167 // except for the last block membeor of an SSBO.
2168 // TODO: If this changes, link-time sized arrays might show up here, and need their
2169 // size extracted.
2170
John Kessenichc9a80832015-09-12 12:17:44 -06002171 // Normal .length() would have been constant folded by the front-end.
2172 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002173 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002174
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002175 spv::Id length;
2176 if (node->getOperand()->getType().isCoopMat()) {
2177 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2178
2179 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2180 assert(builder.isCooperativeMatrixType(typeId));
2181
2182 length = builder.createCooperativeMatrixLength(typeId);
2183 } else {
2184 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2185 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002186 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2187 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002188 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2189 }
John Kessenichc9a80832015-09-12 12:17:44 -06002190
John Kessenich8c869672018-11-28 07:01:37 -07002191 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2192 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2193 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002194 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2195 if (builder.isInSpecConstCodeGenMode()) {
2196 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2197 } else {
2198 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2199 }
2200 }
John Kessenich8c869672018-11-28 07:01:37 -07002201
John Kessenichc9a80832015-09-12 12:17:44 -06002202 builder.clearAccessChain();
2203 builder.setAccessChainRValue(length);
2204
2205 return false;
2206 }
2207
John Kessenichfc51d282015-08-19 13:34:18 -06002208 // Start by evaluating the operand
2209
John Kessenich8c8505c2016-07-26 12:50:38 -06002210 // Does it need a swizzle inversion? If so, evaluation is inverted;
2211 // operate first on the swizzle base, then apply the swizzle.
2212 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002213 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2214 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002215 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2216 invertedType = getInvertedSwizzleType(*node->getOperand());
2217
John Kessenich140f3df2015-06-26 16:58:36 -06002218 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002219 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002220 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002221 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002222 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002223 operandNode = node->getOperand();
2224
2225 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002226
Rex Xufc618912015-09-09 16:42:49 +08002227 spv::Id operand = spv::NoResult;
2228
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002229 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2230
John Kessenichfb4f2332019-08-09 03:49:15 -06002231#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002232 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2233 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002234 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002235 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2236 node->getOp() == glslang::EOpRayQueryProceed ||
2237 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2238 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2239 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2240 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2241 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2242 node->getOp() == glslang::EOpRayQueryTerminate ||
2243 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002244 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002245 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2246 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2247 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002248#endif
2249 {
John Kessenich32cfd492016-02-02 12:37:46 -07002250 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002251 }
John Kessenich140f3df2015-06-26 16:58:36 -06002252
John Kessenichead86222018-03-28 18:01:20 -06002253 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002254 TranslateNoContractionDecoration(node->getType().getQualifier()),
2255 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002256
2257 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002258 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002259 result = createConversion(node->getOp(), decorations, resultType(), operand,
2260 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002261
2262 // if not, then possibly an operation
2263 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002264 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2265 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002266
2267 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002268 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002269 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002270 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002271 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002272
John Kessenich140f3df2015-06-26 16:58:36 -06002273 builder.clearAccessChain();
2274 builder.setAccessChainRValue(result);
2275
2276 return false; // done with this node
2277 }
2278
2279 // it must be a special case, check...
2280 switch (node->getOp()) {
2281 case glslang::EOpPostIncrement:
2282 case glslang::EOpPostDecrement:
2283 case glslang::EOpPreIncrement:
2284 case glslang::EOpPreDecrement:
2285 {
2286 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002287 spv::Id one = 0;
2288 if (node->getBasicType() == glslang::EbtFloat)
2289 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002290#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002291 else if (node->getBasicType() == glslang::EbtDouble)
2292 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002293 else if (node->getBasicType() == glslang::EbtFloat16)
2294 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002295 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2296 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002297 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2298 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002299 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2300 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002301#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002302 else
2303 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002304 glslang::TOperator op;
2305 if (node->getOp() == glslang::EOpPreIncrement ||
2306 node->getOp() == glslang::EOpPostIncrement)
2307 op = glslang::EOpAdd;
2308 else
2309 op = glslang::EOpSub;
2310
John Kessenichead86222018-03-28 18:01:20 -06002311 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002312 convertGlslangToSpvType(node->getType()), operand, one,
2313 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002314 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002315
2316 // The result of operation is always stored, but conditionally the
2317 // consumed result. The consumed result is always an r-value.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002318 builder.accessChainStore(result,
2319 TranslateNonUniformDecoration(node->getOperand()->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06002320 builder.clearAccessChain();
2321 if (node->getOp() == glslang::EOpPreIncrement ||
2322 node->getOp() == glslang::EOpPreDecrement)
2323 builder.setAccessChainRValue(result);
2324 else
2325 builder.setAccessChainRValue(operand);
2326 }
2327
2328 return false;
2329
John Kessenich155d3512019-08-08 23:29:20 -06002330#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002331 case glslang::EOpEmitStreamVertex:
2332 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2333 return false;
2334 case glslang::EOpEndStreamPrimitive:
2335 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2336 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002337 case glslang::EOpRayQueryTerminate:
2338 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2339 return false;
2340 case glslang::EOpRayQueryConfirmIntersection:
2341 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2342 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002343#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002344
2345 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002346 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002347 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002348 }
John Kessenich140f3df2015-06-26 16:58:36 -06002349}
2350
Jeff Bolz53134492019-06-25 13:31:10 -05002351// Construct a composite object, recursively copying members if their types don't match
2352spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2353{
2354 for (int c = 0; c < (int)constituents.size(); ++c) {
2355 spv::Id& constituent = constituents[c];
2356 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2357 spv::Id rType = builder.getTypeId(constituent);
2358 if (lType != rType) {
2359 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2360 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2361 } else if (builder.isStructType(rType)) {
2362 std::vector<spv::Id> rTypeConstituents;
2363 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2364 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002365 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2366 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002367 }
2368 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2369 } else {
2370 assert(builder.isArrayType(rType));
2371 std::vector<spv::Id> rTypeConstituents;
2372 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2373
2374 spv::Id elementRType = builder.getContainedTypeId(rType);
2375 for (int i = 0; i < numrTypeConstituents; ++i) {
2376 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2377 }
2378 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2379 }
2380 }
2381 }
2382 return builder.createCompositeConstruct(resultTypeId, constituents);
2383}
2384
John Kessenich140f3df2015-06-26 16:58:36 -06002385bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2386{
qining27e04a02016-04-14 16:40:20 -04002387 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2388 if (node->getType().getQualifier().isSpecConstant())
2389 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2390
John Kessenichfc51d282015-08-19 13:34:18 -06002391 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002392 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2393 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2394 // SPIR-V, for an out parameter
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002395 std::vector<glslang::TQualifier> complexLValueQualifiers;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002396 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002397
John Kessenich8985fc92020-03-03 10:25:07 -07002398 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2399 invertedType :
2400 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002401
2402 // try texturing
2403 result = createImageTextureFunctionCall(node);
2404 if (result != spv::NoResult) {
2405 builder.clearAccessChain();
2406 builder.setAccessChainRValue(result);
2407
2408 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002409 }
2410#ifndef GLSLANG_WEB
2411 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002412 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002413 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002414 // "imageStore" is a special case, which has no result
2415 return false;
2416 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002417#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002418
John Kessenich140f3df2015-06-26 16:58:36 -06002419 glslang::TOperator binOp = glslang::EOpNull;
2420 bool reduceComparison = true;
2421 bool isMatrix = false;
2422 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002423 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002424
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002425 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2426
John Kessenich140f3df2015-06-26 16:58:36 -06002427 assert(node->getOp());
2428
John Kessenichf6640762016-08-01 19:44:00 -06002429 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002430
2431 switch (node->getOp()) {
2432 case glslang::EOpSequence:
2433 {
2434 if (preVisit)
2435 ++sequenceDepth;
2436 else
2437 --sequenceDepth;
2438
2439 if (sequenceDepth == 1) {
2440 // If this is the parent node of all the functions, we want to see them
2441 // early, so all call points have actual SPIR-V functions to reference.
2442 // In all cases, still let the traverser visit the children for us.
2443 makeFunctions(node->getAsAggregate()->getSequence());
2444
John Kessenich6fccb3c2016-09-19 16:01:41 -06002445 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002446 // anything else gets there, so visit out of order, doing them all now.
2447 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2448
John Kessenich6a60c2f2016-12-08 21:01:59 -07002449 // 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 -06002450 // so do them manually.
2451 visitFunctions(node->getAsAggregate()->getSequence());
2452
2453 return false;
2454 }
2455
2456 return true;
2457 }
2458 case glslang::EOpLinkerObjects:
2459 {
2460 if (visit == glslang::EvPreVisit)
2461 linkageOnly = true;
2462 else
2463 linkageOnly = false;
2464
2465 return true;
2466 }
2467 case glslang::EOpComma:
2468 {
2469 // processing from left to right naturally leaves the right-most
2470 // lying around in the access chain
2471 glslang::TIntermSequence& glslangOperands = node->getSequence();
2472 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2473 glslangOperands[i]->traverse(this);
2474
2475 return false;
2476 }
2477 case glslang::EOpFunction:
2478 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002479 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002480 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002481 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002482 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002483 } else {
2484 handleFunctionEntry(node);
2485 }
2486 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002487 if (inEntryPoint)
2488 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002489 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002490 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002491 }
2492
2493 return true;
2494 case glslang::EOpParameters:
2495 // Parameters will have been consumed by EOpFunction processing, but not
2496 // the body, so we still visited the function node's children, making this
2497 // child redundant.
2498 return false;
2499 case glslang::EOpFunctionCall:
2500 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002501 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002502 if (node->isUserDefined())
2503 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002504 if (result) {
2505 builder.clearAccessChain();
2506 builder.setAccessChainRValue(result);
2507 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002508 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002509
2510 return false;
2511 }
2512 case glslang::EOpConstructMat2x2:
2513 case glslang::EOpConstructMat2x3:
2514 case glslang::EOpConstructMat2x4:
2515 case glslang::EOpConstructMat3x2:
2516 case glslang::EOpConstructMat3x3:
2517 case glslang::EOpConstructMat3x4:
2518 case glslang::EOpConstructMat4x2:
2519 case glslang::EOpConstructMat4x3:
2520 case glslang::EOpConstructMat4x4:
2521 case glslang::EOpConstructDMat2x2:
2522 case glslang::EOpConstructDMat2x3:
2523 case glslang::EOpConstructDMat2x4:
2524 case glslang::EOpConstructDMat3x2:
2525 case glslang::EOpConstructDMat3x3:
2526 case glslang::EOpConstructDMat3x4:
2527 case glslang::EOpConstructDMat4x2:
2528 case glslang::EOpConstructDMat4x3:
2529 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002530 case glslang::EOpConstructIMat2x2:
2531 case glslang::EOpConstructIMat2x3:
2532 case glslang::EOpConstructIMat2x4:
2533 case glslang::EOpConstructIMat3x2:
2534 case glslang::EOpConstructIMat3x3:
2535 case glslang::EOpConstructIMat3x4:
2536 case glslang::EOpConstructIMat4x2:
2537 case glslang::EOpConstructIMat4x3:
2538 case glslang::EOpConstructIMat4x4:
2539 case glslang::EOpConstructUMat2x2:
2540 case glslang::EOpConstructUMat2x3:
2541 case glslang::EOpConstructUMat2x4:
2542 case glslang::EOpConstructUMat3x2:
2543 case glslang::EOpConstructUMat3x3:
2544 case glslang::EOpConstructUMat3x4:
2545 case glslang::EOpConstructUMat4x2:
2546 case glslang::EOpConstructUMat4x3:
2547 case glslang::EOpConstructUMat4x4:
2548 case glslang::EOpConstructBMat2x2:
2549 case glslang::EOpConstructBMat2x3:
2550 case glslang::EOpConstructBMat2x4:
2551 case glslang::EOpConstructBMat3x2:
2552 case glslang::EOpConstructBMat3x3:
2553 case glslang::EOpConstructBMat3x4:
2554 case glslang::EOpConstructBMat4x2:
2555 case glslang::EOpConstructBMat4x3:
2556 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002557 case glslang::EOpConstructF16Mat2x2:
2558 case glslang::EOpConstructF16Mat2x3:
2559 case glslang::EOpConstructF16Mat2x4:
2560 case glslang::EOpConstructF16Mat3x2:
2561 case glslang::EOpConstructF16Mat3x3:
2562 case glslang::EOpConstructF16Mat3x4:
2563 case glslang::EOpConstructF16Mat4x2:
2564 case glslang::EOpConstructF16Mat4x3:
2565 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002566 isMatrix = true;
2567 // fall through
2568 case glslang::EOpConstructFloat:
2569 case glslang::EOpConstructVec2:
2570 case glslang::EOpConstructVec3:
2571 case glslang::EOpConstructVec4:
2572 case glslang::EOpConstructDouble:
2573 case glslang::EOpConstructDVec2:
2574 case glslang::EOpConstructDVec3:
2575 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002576 case glslang::EOpConstructFloat16:
2577 case glslang::EOpConstructF16Vec2:
2578 case glslang::EOpConstructF16Vec3:
2579 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002580 case glslang::EOpConstructBool:
2581 case glslang::EOpConstructBVec2:
2582 case glslang::EOpConstructBVec3:
2583 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002584 case glslang::EOpConstructInt8:
2585 case glslang::EOpConstructI8Vec2:
2586 case glslang::EOpConstructI8Vec3:
2587 case glslang::EOpConstructI8Vec4:
2588 case glslang::EOpConstructUint8:
2589 case glslang::EOpConstructU8Vec2:
2590 case glslang::EOpConstructU8Vec3:
2591 case glslang::EOpConstructU8Vec4:
2592 case glslang::EOpConstructInt16:
2593 case glslang::EOpConstructI16Vec2:
2594 case glslang::EOpConstructI16Vec3:
2595 case glslang::EOpConstructI16Vec4:
2596 case glslang::EOpConstructUint16:
2597 case glslang::EOpConstructU16Vec2:
2598 case glslang::EOpConstructU16Vec3:
2599 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002600 case glslang::EOpConstructInt:
2601 case glslang::EOpConstructIVec2:
2602 case glslang::EOpConstructIVec3:
2603 case glslang::EOpConstructIVec4:
2604 case glslang::EOpConstructUint:
2605 case glslang::EOpConstructUVec2:
2606 case glslang::EOpConstructUVec3:
2607 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002608 case glslang::EOpConstructInt64:
2609 case glslang::EOpConstructI64Vec2:
2610 case glslang::EOpConstructI64Vec3:
2611 case glslang::EOpConstructI64Vec4:
2612 case glslang::EOpConstructUint64:
2613 case glslang::EOpConstructU64Vec2:
2614 case glslang::EOpConstructU64Vec3:
2615 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002616 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002617 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002618 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002619 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002620 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002621 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002622 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002623 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002624 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002625 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002626 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002627 else if (node->getOp() == glslang::EOpConstructStruct ||
2628 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2629 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002630 std::vector<spv::Id> constituents;
2631 for (int c = 0; c < (int)arguments.size(); ++c)
2632 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002633 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002634 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002635 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002636 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002637 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002638
Bas Nieuwenhuizenc9ffeec2020-09-03 03:09:39 +02002639 if (node->getType().getQualifier().isNonUniform()) {
2640 builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
2641 }
2642
John Kessenich140f3df2015-06-26 16:58:36 -06002643 builder.clearAccessChain();
2644 builder.setAccessChainRValue(constructed);
2645
2646 return false;
2647 }
2648
2649 // These six are component-wise compares with component-wise results.
2650 // Forward on to createBinaryOperation(), requesting a vector result.
2651 case glslang::EOpLessThan:
2652 case glslang::EOpGreaterThan:
2653 case glslang::EOpLessThanEqual:
2654 case glslang::EOpGreaterThanEqual:
2655 case glslang::EOpVectorEqual:
2656 case glslang::EOpVectorNotEqual:
2657 {
2658 // Map the operation to a binary
2659 binOp = node->getOp();
2660 reduceComparison = false;
2661 switch (node->getOp()) {
2662 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2663 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2664 default: binOp = node->getOp(); break;
2665 }
2666
2667 break;
2668 }
2669 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002670 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002671 binOp = glslang::EOpMul;
2672 break;
2673 case glslang::EOpOuterProduct:
2674 // two vectors multiplied to make a matrix
2675 binOp = glslang::EOpOuterProduct;
2676 break;
2677 case glslang::EOpDot:
2678 {
qining25262b32016-05-06 17:25:16 -04002679 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002680 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002681 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002682 binOp = glslang::EOpMul;
2683 break;
2684 }
2685 case glslang::EOpMod:
2686 // when an aggregate, this is the floating-point mod built-in function,
2687 // which can be emitted by the one in createBinaryOperation()
2688 binOp = glslang::EOpMod;
2689 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002690
John Kessenich140f3df2015-06-26 16:58:36 -06002691 case glslang::EOpEmitVertex:
2692 case glslang::EOpEndPrimitive:
2693 case glslang::EOpBarrier:
2694 case glslang::EOpMemoryBarrier:
2695 case glslang::EOpMemoryBarrierAtomicCounter:
2696 case glslang::EOpMemoryBarrierBuffer:
2697 case glslang::EOpMemoryBarrierImage:
2698 case glslang::EOpMemoryBarrierShared:
2699 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002700 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002701 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002702 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002703 case glslang::EOpWorkgroupMemoryBarrier:
2704 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002705 case glslang::EOpSubgroupBarrier:
2706 case glslang::EOpSubgroupMemoryBarrier:
2707 case glslang::EOpSubgroupMemoryBarrierBuffer:
2708 case glslang::EOpSubgroupMemoryBarrierImage:
2709 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002710 noReturnValue = true;
2711 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2712 break;
2713
John Kessenich426394d2015-07-23 10:22:48 -06002714 case glslang::EOpAtomicAdd:
2715 case glslang::EOpAtomicMin:
2716 case glslang::EOpAtomicMax:
2717 case glslang::EOpAtomicAnd:
2718 case glslang::EOpAtomicOr:
2719 case glslang::EOpAtomicXor:
2720 case glslang::EOpAtomicExchange:
2721 case glslang::EOpAtomicCompSwap:
2722 atomic = true;
2723 break;
2724
John Kesseniche5eee8f2019-10-18 01:03:11 -06002725#ifndef GLSLANG_WEB
2726 case glslang::EOpAtomicStore:
2727 noReturnValue = true;
2728 // fallthrough
2729 case glslang::EOpAtomicLoad:
2730 atomic = true;
2731 break;
2732
John Kessenich0d0c6d32017-07-23 16:08:26 -06002733 case glslang::EOpAtomicCounterAdd:
2734 case glslang::EOpAtomicCounterSubtract:
2735 case glslang::EOpAtomicCounterMin:
2736 case glslang::EOpAtomicCounterMax:
2737 case glslang::EOpAtomicCounterAnd:
2738 case glslang::EOpAtomicCounterOr:
2739 case glslang::EOpAtomicCounterXor:
2740 case glslang::EOpAtomicCounterExchange:
2741 case glslang::EOpAtomicCounterCompSwap:
2742 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2743 builder.addCapability(spv::CapabilityAtomicStorageOps);
2744 atomic = true;
2745 break;
2746
Ian Romanickb3bd4022019-01-21 08:57:25 -08002747 case glslang::EOpAbsDifference:
2748 case glslang::EOpAddSaturate:
2749 case glslang::EOpSubSaturate:
2750 case glslang::EOpAverage:
2751 case glslang::EOpAverageRounded:
2752 case glslang::EOpMul32x16:
2753 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2754 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2755 binOp = node->getOp();
2756 break;
2757
Daniel Kochdb32b242020-03-17 20:42:47 -04002758 case glslang::EOpIgnoreIntersection:
2759 case glslang::EOpTerminateRay:
2760 case glslang::EOpTrace:
2761 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002762 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2763 noReturnValue = true;
2764 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002765 case glslang::EOpRayQueryInitialize:
2766 case glslang::EOpRayQueryTerminate:
2767 case glslang::EOpRayQueryGenerateIntersection:
2768 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002769 builder.addExtension("SPV_KHR_ray_query");
2770 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002771 noReturnValue = true;
2772 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002773 case glslang::EOpRayQueryProceed:
2774 case glslang::EOpRayQueryGetIntersectionType:
2775 case glslang::EOpRayQueryGetRayTMin:
2776 case glslang::EOpRayQueryGetRayFlags:
2777 case glslang::EOpRayQueryGetIntersectionT:
2778 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2779 case glslang::EOpRayQueryGetIntersectionInstanceId:
2780 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2781 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2782 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2783 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2784 case glslang::EOpRayQueryGetIntersectionFrontFace:
2785 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2786 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2787 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2788 case glslang::EOpRayQueryGetWorldRayDirection:
2789 case glslang::EOpRayQueryGetWorldRayOrigin:
2790 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2791 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2792 builder.addExtension("SPV_KHR_ray_query");
2793 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2794 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002795 case glslang::EOpCooperativeMatrixLoad:
2796 case glslang::EOpCooperativeMatrixStore:
2797 noReturnValue = true;
2798 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002799 case glslang::EOpBeginInvocationInterlock:
2800 case glslang::EOpEndInvocationInterlock:
2801 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2802 noReturnValue = true;
2803 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002804#endif
Chao Chen3c366992018-09-19 11:41:59 -07002805
Jeff Bolz04d73732019-05-31 13:06:01 -05002806 case glslang::EOpDebugPrintf:
2807 noReturnValue = true;
2808 break;
2809
John Kessenich140f3df2015-06-26 16:58:36 -06002810 default:
2811 break;
2812 }
2813
2814 //
2815 // See if it maps to a regular operation.
2816 //
John Kessenich140f3df2015-06-26 16:58:36 -06002817 if (binOp != glslang::EOpNull) {
2818 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2819 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2820 assert(left && right);
2821
2822 builder.clearAccessChain();
2823 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002824 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002825
2826 builder.clearAccessChain();
2827 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002828 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002829
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002830 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002831 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002832 TranslateNoContractionDecoration(node->getType().getQualifier()),
2833 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002834 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002835 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002836 left->getType().getBasicType(), reduceComparison);
2837
2838 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002839 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002840 builder.clearAccessChain();
2841 builder.setAccessChainRValue(result);
2842
2843 return false;
2844 }
2845
John Kessenich426394d2015-07-23 10:22:48 -06002846 //
2847 // Create the list of operands.
2848 //
John Kessenich140f3df2015-06-26 16:58:36 -06002849 glslang::TIntermSequence& glslangOperands = node->getSequence();
2850 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002851 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002852 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002853 // special case l-value operands; there are just a few
2854 bool lvalue = false;
2855 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002856 case glslang::EOpModf:
2857 if (arg == 1)
2858 lvalue = true;
2859 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002860
Torosdagli06c2eee2020-03-19 11:09:57 -04002861 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002862 case glslang::EOpRayQueryTerminate:
2863 case glslang::EOpRayQueryConfirmIntersection:
2864 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002865 case glslang::EOpRayQueryGenerateIntersection:
2866 case glslang::EOpRayQueryGetIntersectionType:
2867 case glslang::EOpRayQueryGetIntersectionT:
2868 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2869 case glslang::EOpRayQueryGetIntersectionInstanceId:
2870 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2871 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2872 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2873 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2874 case glslang::EOpRayQueryGetIntersectionFrontFace:
2875 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2876 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2877 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2878 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2879 if (arg == 0)
2880 lvalue = true;
2881 break;
2882
John Kesseniche5eee8f2019-10-18 01:03:11 -06002883 case glslang::EOpAtomicAdd:
2884 case glslang::EOpAtomicMin:
2885 case glslang::EOpAtomicMax:
2886 case glslang::EOpAtomicAnd:
2887 case glslang::EOpAtomicOr:
2888 case glslang::EOpAtomicXor:
2889 case glslang::EOpAtomicExchange:
2890 case glslang::EOpAtomicCompSwap:
2891 if (arg == 0)
2892 lvalue = true;
2893 break;
2894
John Kessenicha28f7a72019-08-06 07:00:58 -06002895#ifndef GLSLANG_WEB
2896 case glslang::EOpFrexp:
2897 if (arg == 1)
2898 lvalue = true;
2899 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002900 case glslang::EOpInterpolateAtSample:
2901 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002902 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002903 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002904 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002905
2906 // Does it need a swizzle inversion? If so, evaluation is inverted;
2907 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002908 // That is, we transform
2909 //
2910 // interpolate(v.zy) -> interpolate(v).zy
2911 //
John Kessenichecba76f2017-01-06 00:34:48 -07002912 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002913 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002914 invertedType = convertGlslangToSpvType(
2915 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002916 }
Rex Xu7a26c172015-12-08 17:12:09 +08002917 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002918 case glslang::EOpAtomicLoad:
2919 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002920 case glslang::EOpAtomicCounterAdd:
2921 case glslang::EOpAtomicCounterSubtract:
2922 case glslang::EOpAtomicCounterMin:
2923 case glslang::EOpAtomicCounterMax:
2924 case glslang::EOpAtomicCounterAnd:
2925 case glslang::EOpAtomicCounterOr:
2926 case glslang::EOpAtomicCounterXor:
2927 case glslang::EOpAtomicCounterExchange:
2928 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002929 if (arg == 0)
2930 lvalue = true;
2931 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002932 case glslang::EOpAddCarry:
2933 case glslang::EOpSubBorrow:
2934 if (arg == 2)
2935 lvalue = true;
2936 break;
2937 case glslang::EOpUMulExtended:
2938 case glslang::EOpIMulExtended:
2939 if (arg >= 2)
2940 lvalue = true;
2941 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002942 case glslang::EOpCooperativeMatrixLoad:
2943 if (arg == 0 || arg == 1)
2944 lvalue = true;
2945 break;
2946 case glslang::EOpCooperativeMatrixStore:
2947 if (arg == 1)
2948 lvalue = true;
2949 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002950#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002951 default:
2952 break;
2953 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002954 builder.clearAccessChain();
2955 if (invertedType != spv::NoType && arg == 0)
2956 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2957 else
2958 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002959
John Kessenichb9197c82019-08-11 07:41:45 -06002960#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002961 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2962 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2963
2964 if (arg == 1) {
2965 // fold "element" parameter into the access chain
2966 spv::Builder::AccessChain save = builder.getAccessChain();
2967 builder.clearAccessChain();
2968 glslangOperands[2]->traverse(this);
2969
2970 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2971
2972 builder.setAccessChain(save);
2973
2974 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002975 builder.accessChainPush(elementId,
2976 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2977 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002978
2979 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2980 unsigned int alignment = builder.getAccessChain().alignment;
2981
2982 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2983 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2984 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2985 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2986 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002987 if (builder.getStorageClass(builder.getAccessChain().base) ==
2988 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002989 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2990 }
2991
2992 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2993
2994 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2995 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2996 }
2997
John Kessenich8985fc92020-03-03 10:25:07 -07002998 if (memoryAccess &
2999 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
3000 memoryAccessOperands.push_back(spv::IdImmediate(true,
3001 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003002 }
3003 } else if (arg == 2) {
3004 continue;
3005 }
3006 }
John Kessenichb9197c82019-08-11 07:41:45 -06003007#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003008
John Kessenichbbbd9a22020-03-03 07:21:37 -07003009 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003010 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07003011 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
3012 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
3013 // reduce to a simple access chain. So, we need a temporary vector to
3014 // receive the result, and must later swizzle that into the original
3015 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06003016 complexLvalues.push_back(builder.getAccessChain());
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003017 complexLValueQualifiers.push_back(glslangOperands[arg]->getAsTyped()->getType().getQualifier());
John Kessenich435dd802020-06-30 01:27:08 -06003018 temporaryLvalues.push_back(builder.createVariable(
3019 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003020 builder.accessChainGetInferredType(), "swizzleTemp"));
3021 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003022 } else {
3023 operands.push_back(builder.accessChainGetLValue());
3024 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003025 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3026 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3027 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003028 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003029 glslang::TOperator glslangOp = node->getOp();
3030 if (arg == 1 &&
3031 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3032 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3033 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3034 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3035 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3036 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3037 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3038 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3039 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3040 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3041 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3042 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3043 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3044 )) {
3045 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3046 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3047 }
3048 else {
3049 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3050 }
3051
John Kesseniche485c7a2017-05-31 18:50:53 -06003052 }
John Kessenich140f3df2015-06-26 16:58:36 -06003053 }
John Kessenich426394d2015-07-23 10:22:48 -06003054
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003055 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003056#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003057 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3058 std::vector<spv::IdImmediate> idImmOps;
3059
3060 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3061 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3062 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3063 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3064 // get the pointee type
3065 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3066 assert(builder.isCooperativeMatrixType(typeId));
3067 // do the op
3068 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3069 // store the result to the pointer (out param 'm')
3070 builder.createStore(result, operands[0]);
3071 result = 0;
3072 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3073 std::vector<spv::IdImmediate> idImmOps;
3074
3075 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3076 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3077 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3078 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3079 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3080
3081 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3082 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003083 } else
3084#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003085 if (atomic) {
3086 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003087 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3088 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003089 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3090 if (!nonSemanticDebugPrintf) {
3091 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3092 }
3093 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3094 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003095 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003096 // Pass through to generic operations.
3097 switch (glslangOperands.size()) {
3098 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003099 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003100 break;
3101 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003102 {
3103 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003104 TranslateNoContractionDecoration(node->getType().getQualifier()),
3105 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003106 result = createUnaryOperation(
3107 node->getOp(), decorations,
3108 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003109 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003110 }
John Kessenich426394d2015-07-23 10:22:48 -06003111 break;
3112 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003113 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003114 break;
3115 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003116
John Kessenichbbbd9a22020-03-03 07:21:37 -07003117 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003118 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003119
3120 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3121 builder.setAccessChain(complexLvalues[i]);
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003122 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision), TranslateNonUniformDecoration(complexLValueQualifiers[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003123 }
John Kessenich140f3df2015-06-26 16:58:36 -06003124 }
3125
3126 if (noReturnValue)
3127 return false;
3128
3129 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003130 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003131 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003132 } else {
3133 builder.clearAccessChain();
3134 builder.setAccessChainRValue(result);
3135 return false;
3136 }
3137}
3138
John Kessenich433e9ff2017-01-26 20:31:11 -07003139// This path handles both if-then-else and ?:
3140// The if-then-else has a node type of void, while
3141// ?: has either a void or a non-void node type
3142//
3143// Leaving the result, when not void:
3144// GLSL only has r-values as the result of a :?, but
3145// if we have an l-value, that can be more efficient if it will
3146// become the base of a complex r-value expression, because the
3147// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003148bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3149{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003150 // see if OpSelect can handle it
3151 const auto isOpSelectable = [&]() {
3152 if (node->getBasicType() == glslang::EbtVoid)
3153 return false;
3154 // OpSelect can do all other types starting with SPV 1.4
3155 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3156 // pre-1.4, only scalars and vectors can be handled
3157 if ((!node->getType().isScalar() && !node->getType().isVector()))
3158 return false;
3159 }
3160 return true;
3161 };
3162
John Kessenich4bee5312018-02-20 21:29:05 -07003163 // See if it simple and safe, or required, to execute both sides.
3164 // Crucially, side effects must be either semantically required or avoided,
3165 // and there are performance trade-offs.
3166 // Return true if required or a good idea (and safe) to execute both sides,
3167 // false otherwise.
3168 const auto bothSidesPolicy = [&]() -> bool {
3169 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003170 if (node->getTrueBlock() == nullptr ||
3171 node->getFalseBlock() == nullptr)
3172 return false;
3173
John Kessenich4bee5312018-02-20 21:29:05 -07003174 // required? (unless we write additional code to look for side effects
3175 // and make performance trade-offs if none are present)
3176 if (!node->getShortCircuit())
3177 return true;
3178
3179 // if not required to execute both, decide based on performance/practicality...
3180
John Kessenich0c1e71a2019-01-10 18:23:06 +07003181 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003182 return false;
3183
John Kessenich433e9ff2017-01-26 20:31:11 -07003184 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3185 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3186
3187 // return true if a single operand to ? : is okay for OpSelect
3188 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003189 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003190 };
3191
3192 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3193 operandOkay(node->getFalseBlock()->getAsTyped());
3194 };
3195
John Kessenich4bee5312018-02-20 21:29:05 -07003196 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3197 // emit the condition before doing anything with selection
3198 node->getCondition()->traverse(this);
3199 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3200
3201 // Find a way of executing both sides and selecting the right result.
3202 const auto executeBothSides = [&]() -> void {
3203 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003204 node->getTrueBlock()->traverse(this);
3205 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3206 node->getFalseBlock()->traverse(this);
3207 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3208
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003209 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003210
John Kessenich4bee5312018-02-20 21:29:05 -07003211 // done if void
3212 if (node->getBasicType() == glslang::EbtVoid)
3213 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003214
John Kessenich4bee5312018-02-20 21:29:05 -07003215 // emit code to select between trueValue and falseValue
3216
3217 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003218 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003219 // Emit OpSelect for this selection.
3220
3221 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003222 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3223 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003224 condition = builder.smearScalar(spv::NoPrecision, condition,
3225 builder.makeVectorType(builder.makeBoolType(),
3226 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003227 }
John Kessenich4bee5312018-02-20 21:29:05 -07003228
3229 // OpSelect
3230 result = builder.createTriOp(spv::OpSelect,
3231 convertGlslangToSpvType(node->getType()), condition,
3232 trueValue, falseValue);
3233
3234 builder.clearAccessChain();
3235 builder.setAccessChainRValue(result);
3236 } else {
3237 // We need control flow to select the result.
3238 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003239 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3240 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003241
3242 // Selection control:
3243 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3244
3245 // make an "if" based on the value created by the condition
3246 spv::Builder::If ifBuilder(condition, control, builder);
3247
3248 // emit the "then" statement
3249 builder.createStore(trueValue, result);
3250 ifBuilder.makeBeginElse();
3251 // emit the "else" statement
3252 builder.createStore(falseValue, result);
3253
3254 // finish off the control flow
3255 ifBuilder.makeEndIf();
3256
3257 builder.clearAccessChain();
3258 builder.setAccessChainLValue(result);
3259 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003260 };
3261
John Kessenich4bee5312018-02-20 21:29:05 -07003262 // Execute the one side needed, as per the condition
3263 const auto executeOneSide = [&]() {
3264 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003265 if (node->getBasicType() != glslang::EbtVoid) {
3266 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3267 convertGlslangToSpvType(node->getType()));
3268 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003269
John Kessenich4bee5312018-02-20 21:29:05 -07003270 // Selection control:
3271 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3272
3273 // make an "if" based on the value created by the condition
3274 spv::Builder::If ifBuilder(condition, control, builder);
3275
3276 // emit the "then" statement
3277 if (node->getTrueBlock() != nullptr) {
3278 node->getTrueBlock()->traverse(this);
3279 if (result != spv::NoResult)
3280 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3281 }
3282
3283 if (node->getFalseBlock() != nullptr) {
3284 ifBuilder.makeBeginElse();
3285 // emit the "else" statement
3286 node->getFalseBlock()->traverse(this);
3287 if (result != spv::NoResult)
3288 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3289 }
3290
3291 // finish off the control flow
3292 ifBuilder.makeEndIf();
3293
3294 if (result != spv::NoResult) {
3295 builder.clearAccessChain();
3296 builder.setAccessChainLValue(result);
3297 }
3298 };
3299
3300 // Try for OpSelect (or a requirement to execute both sides)
3301 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003302 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3303 if (node->getType().getQualifier().isSpecConstant())
3304 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003305 executeBothSides();
3306 } else
3307 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003308
3309 return false;
3310}
3311
3312bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3313{
3314 // emit and get the condition before doing anything with switch
3315 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003316 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003317
Rex Xu57e65922017-07-04 23:23:40 +08003318 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003319 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003320
John Kessenich140f3df2015-06-26 16:58:36 -06003321 // browse the children to sort out code segments
3322 int defaultSegment = -1;
3323 std::vector<TIntermNode*> codeSegments;
3324 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3325 std::vector<int> caseValues;
3326 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3327 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3328 TIntermNode* child = *c;
3329 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003330 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003331 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003332 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003333 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3334 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003335 } else
3336 codeSegments.push_back(child);
3337 }
3338
qining25262b32016-05-06 17:25:16 -04003339 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003340 // statements between the last case and the end of the switch statement
3341 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3342 (int)codeSegments.size() == defaultSegment)
3343 codeSegments.push_back(nullptr);
3344
3345 // make the switch statement
3346 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003347 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3348 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003349
3350 // emit all the code in the segments
3351 breakForLoop.push(false);
3352 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3353 builder.nextSwitchSegment(segmentBlocks, s);
3354 if (codeSegments[s])
3355 codeSegments[s]->traverse(this);
3356 else
3357 builder.addSwitchBreak();
3358 }
3359 breakForLoop.pop();
3360
3361 builder.endSwitch(segmentBlocks);
3362
3363 return false;
3364}
3365
3366void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3367{
3368 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003369 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003370
3371 builder.clearAccessChain();
3372 builder.setAccessChainRValue(constant);
3373}
3374
3375bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3376{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003377 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003378 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003379
3380 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003381 std::vector<unsigned int> operands;
3382 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003383
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003384 // Spec requires back edges to target header blocks, and every header block
3385 // must dominate its merge block. Make a header block first to ensure these
3386 // conditions are met. By definition, it will contain OpLoopMerge, followed
3387 // by a block-ending branch. But we don't want to put any other body/test
3388 // instructions in it, since the body/test may have arbitrary instructions,
3389 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003390 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003391 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003392 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003393 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003394 spv::Block& test = builder.makeNewBlock();
3395 builder.createBranch(&test);
3396
3397 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003398 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003399 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003400 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3401
3402 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003403 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003404 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003405 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003406 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003407 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003408
3409 builder.setBuildPoint(&blocks.continue_target);
3410 if (node->getTerminal())
3411 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003412 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003413 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003414 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003415 builder.createBranch(&blocks.body);
3416
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003417 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003418 builder.setBuildPoint(&blocks.body);
3419 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003420 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003421 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003422 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003423
3424 builder.setBuildPoint(&blocks.continue_target);
3425 if (node->getTerminal())
3426 node->getTerminal()->traverse(this);
3427 if (node->getTest()) {
3428 node->getTest()->traverse(this);
3429 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003430 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003431 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003432 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003433 // TODO: unless there was a break/return/discard instruction
3434 // somewhere in the body, this is an infinite loop, so we should
3435 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003436 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003437 }
John Kessenich140f3df2015-06-26 16:58:36 -06003438 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003439 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003440 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003441 return false;
3442}
3443
3444bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3445{
3446 if (node->getExpression())
3447 node->getExpression()->traverse(this);
3448
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003449 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003450
John Kessenich140f3df2015-06-26 16:58:36 -06003451 switch (node->getFlowOp()) {
3452 case glslang::EOpKill:
3453 builder.makeDiscard();
3454 break;
3455 case glslang::EOpBreak:
3456 if (breakForLoop.top())
3457 builder.createLoopExit();
3458 else
3459 builder.addSwitchBreak();
3460 break;
3461 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003462 builder.createLoopContinue();
3463 break;
3464 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003465 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003466 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3467 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003468 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3469 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003470 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003471 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3472 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003473 builder.setAccessChainLValue(copyId);
3474 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003475 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003476 }
3477 builder.makeReturn(false, returnId);
3478 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003479 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003480
3481 builder.clearAccessChain();
3482 break;
3483
John Kessenichb9197c82019-08-11 07:41:45 -06003484#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003485 case glslang::EOpDemote:
3486 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3487 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3488 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3489 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003490#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003491
John Kessenich140f3df2015-06-26 16:58:36 -06003492 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003493 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003494 break;
3495 }
3496
3497 return false;
3498}
3499
John Kessenich9c14f772019-06-17 08:38:35 -06003500spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003501{
qining25262b32016-05-06 17:25:16 -04003502 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003503 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003504 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003505 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003506 spv::Id result = createSpvConstant(*node);
3507 if (result != spv::NoResult)
3508 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003509 }
3510
3511 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003512 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003513 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3514 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003515
John Kessenichb9197c82019-08-11 07:41:45 -06003516 const bool contains16BitType = node->getType().contains16BitFloat() ||
3517 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003518 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003519 switch (storageClass) {
3520 case spv::StorageClassInput:
3521 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003522 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003523 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003524 break;
John Kessenich18310872018-05-14 22:08:53 -06003525 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003526 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003527 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3528 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003529 else
3530 builder.addCapability(spv::CapabilityStorageUniform16);
3531 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003532#ifndef GLSLANG_WEB
3533 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003534 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003535 builder.addCapability(spv::CapabilityStoragePushConstant16);
3536 break;
John Kessenich18310872018-05-14 22:08:53 -06003537 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003538 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003539 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003540 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3541 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003542#endif
John Kessenich18310872018-05-14 22:08:53 -06003543 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003544 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003545 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003546 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003547 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003548 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003549 }
3550 }
Rex Xuf89ad982017-04-07 23:22:33 +08003551
John Kessenichb9197c82019-08-11 07:41:45 -06003552 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003553 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003554 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003555 builder.addCapability(spv::CapabilityStoragePushConstant8);
3556 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003557 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003558 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003559 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003560 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003561 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003562 } else {
3563 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003564 }
3565 }
3566
John Kessenich140f3df2015-06-26 16:58:36 -06003567 const char* name = node->getName().c_str();
3568 if (glslang::IsAnonymous(name))
3569 name = "";
3570
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003571 spv::Id initializer = spv::NoResult;
3572
3573 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3574 !node->getConstArray().empty()) {
3575 int nextConst = 0;
3576 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3577 node->getConstArray(),
3578 nextConst,
3579 false /* specConst */);
3580 }
3581
John Kessenich435dd802020-06-30 01:27:08 -06003582 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003583}
3584
3585// Return type Id of the sampled type.
3586spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3587{
3588 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003589 case glslang::EbtInt: return builder.makeIntType(32);
3590 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003591 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003592#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003593 case glslang::EbtFloat16:
3594 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3595 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3596 return builder.makeFloatType(16);
3597#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003598 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003599 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003600 return builder.makeFloatType(32);
3601 }
3602}
3603
John Kessenich8c8505c2016-07-26 12:50:38 -06003604// If node is a swizzle operation, return the type that should be used if
3605// the swizzle base is first consumed by another operation, before the swizzle
3606// is applied.
3607spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3608{
John Kessenichecba76f2017-01-06 00:34:48 -07003609 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003610 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3611 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3612 else
3613 return spv::NoType;
3614}
3615
3616// When inverting a swizzle with a parent op, this function
3617// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003618spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3619 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003620{
3621 std::vector<unsigned> swizzle;
3622 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3623 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3624}
3625
John Kessenich8c8505c2016-07-26 12:50:38 -06003626// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3627void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3628{
3629 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3630 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3631 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3632}
3633
John Kessenich3ac051e2015-12-20 11:29:16 -07003634// Convert from a glslang type to an SPV type, by calling into a
3635// recursive version of this function. This establishes the inherited
3636// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003637spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003638{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003639 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003640}
3641
3642// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003643// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003644// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003645spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003646 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3647 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003648{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003649 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003650
3651 switch (type.getBasicType()) {
3652 case glslang::EbtVoid:
3653 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003654 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003655 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003656 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003657 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3658 // a 32-bit int where non-0 means true.
3659 if (explicitLayout != glslang::ElpNone)
3660 spvType = builder.makeUintType(32);
3661 else
3662 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003663 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003664 case glslang::EbtInt:
3665 spvType = builder.makeIntType(32);
3666 break;
3667 case glslang::EbtUint:
3668 spvType = builder.makeUintType(32);
3669 break;
3670 case glslang::EbtFloat:
3671 spvType = builder.makeFloatType(32);
3672 break;
3673#ifndef GLSLANG_WEB
3674 case glslang::EbtDouble:
3675 spvType = builder.makeFloatType(64);
3676 break;
3677 case glslang::EbtFloat16:
3678 spvType = builder.makeFloatType(16);
3679 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003680 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003681 spvType = builder.makeIntType(8);
3682 break;
3683 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003684 spvType = builder.makeUintType(8);
3685 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003686 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003687 spvType = builder.makeIntType(16);
3688 break;
3689 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003690 spvType = builder.makeUintType(16);
3691 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003692 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003693 spvType = builder.makeIntType(64);
3694 break;
3695 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003696 spvType = builder.makeUintType(64);
3697 break;
John Kessenich426394d2015-07-23 10:22:48 -06003698 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003699 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003700 spvType = builder.makeUintType(32);
3701 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003702 case glslang::EbtAccStruct:
3703 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003704 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003705 case glslang::EbtRayQuery:
3706 spvType = builder.makeRayQueryType();
3707 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003708 case glslang::EbtReference:
3709 {
3710 // Make the forward pointer, then recurse to convert the structure type, then
3711 // patch up the forward pointer with a real pointer type.
3712 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3713 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3714 forwardPointers[type.getReferentType()] = forwardId;
3715 }
3716 spvType = forwardPointers[type.getReferentType()];
3717 if (!forwardReferenceOnly) {
3718 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3719 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3720 forwardPointers[type.getReferentType()],
3721 referentType);
3722 }
3723 }
3724 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003725#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003726 case glslang::EbtSampler:
3727 {
3728 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003729 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003730 spvType = builder.makeSamplerType();
3731 } else {
3732 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003733 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3734 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3735 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3736 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003737 // already has both image and sampler, make the combined type
3738 spvType = builder.makeSampledImageType(spvType);
3739 }
John Kessenich55e7d112015-11-15 21:33:39 -07003740 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003741 }
John Kessenich140f3df2015-06-26 16:58:36 -06003742 break;
3743 case glslang::EbtStruct:
3744 case glslang::EbtBlock:
3745 {
3746 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003747 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003748
3749 // Try to share structs for different layouts, but not yet for other
3750 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003751 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003752 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003753 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003754 break;
3755
3756 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003757 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003758 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003759 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003760 }
3761 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003762 case glslang::EbtString:
3763 // no type used for OpString
3764 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003766 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003767 break;
3768 }
3769
3770 if (type.isMatrix())
3771 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3772 else {
3773 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3774 if (type.getVectorSize() > 1)
3775 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3776 }
3777
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003778 if (type.isCoopMat()) {
3779 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3780 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3781 if (type.getBasicType() == glslang::EbtFloat16)
3782 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003783 if (type.getBasicType() == glslang::EbtUint8 ||
3784 type.getBasicType() == glslang::EbtInt8) {
3785 builder.addCapability(spv::CapabilityInt8);
3786 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003787
3788 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3789 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3790 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3791
3792 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3793 }
3794
John Kessenich140f3df2015-06-26 16:58:36 -06003795 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003796 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3797
John Kessenichc9a80832015-09-12 12:17:44 -06003798 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003799 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003800 // We need to decorate array strides for types needing explicit layout, except blocks.
3801 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003802 // Use a dummy glslang type for querying internal strides of
3803 // arrays of arrays, but using just a one-dimensional array.
3804 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003805 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3806 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003807
3808 // Will compute the higher-order strides here, rather than making a whole
3809 // pile of types and doing repetitive recursion on their contents.
3810 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3811 }
John Kessenichf8842e52016-01-04 19:22:56 -07003812
3813 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003814 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003815 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003816 if (stride > 0)
3817 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003818 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003819 }
3820 } else {
3821 // single-dimensional array, and don't yet have stride
3822
John Kessenichf8842e52016-01-04 19:22:56 -07003823 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003824 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3825 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003826 }
John Kessenich31ed4832015-09-09 17:51:38 -06003827
John Kessenichead86222018-03-28 18:01:20 -06003828 // Do the outer dimension, which might not be known for a runtime-sized array.
3829 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3830 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003831 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003832 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003833#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003834 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003835 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003836 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3837 }
John Kessenichb9197c82019-08-11 07:41:45 -06003838#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003839 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003840 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003841 if (stride > 0)
3842 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003843 }
3844
3845 return spvType;
3846}
3847
John Kessenich0e737842017-03-24 18:38:16 -06003848// TODO: this functionality should exist at a higher level, in creating the AST
3849//
3850// Identify interface members that don't have their required extension turned on.
3851//
3852bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3853{
John Kessenicha28f7a72019-08-06 07:00:58 -06003854#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003855 auto& extensions = glslangIntermediate->getRequestedExtensions();
3856
Rex Xubcf291a2017-03-29 23:01:36 +08003857 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3858 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3859 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003860 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3861 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3862 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003863
3864 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3865 if (member.getFieldName() == "gl_ViewportMask" &&
3866 extensions.find("GL_NV_viewport_array2") == extensions.end())
3867 return true;
3868 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3869 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3870 return true;
3871 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3872 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3873 return true;
3874 }
3875#endif
John Kessenich0e737842017-03-24 18:38:16 -06003876
3877 return false;
3878};
3879
John Kessenich6090df02016-06-30 21:18:02 -06003880// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3881// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3882// Mutually recursive with convertGlslangToSpvType().
3883spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3884 const glslang::TTypeList* glslangMembers,
3885 glslang::TLayoutPacking explicitLayout,
3886 const glslang::TQualifier& qualifier)
3887{
3888 // Create a vector of struct types for SPIR-V to consume
3889 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003890 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3891 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003892 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003893 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3894 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3895 if (glslangMember.hiddenMember()) {
3896 ++memberDelta;
3897 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003898 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003899 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003900 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003901 if (filterMember(glslangMember)) {
3902 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003903 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003904 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003905 }
Roy05a5b532020-01-03 16:21:34 +08003906 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003907 }
John Kessenich6090df02016-06-30 21:18:02 -06003908 // modify just this child's view of the qualifier
3909 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3910 InheritQualifiers(memberQualifier, qualifier);
3911
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003912 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003913 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003914 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003915
3916 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003917 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3918 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003919
3920 // Make forward pointers for any pointer members, and create a list of members to
3921 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003922 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003923 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3924 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3925 }
3926 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003927 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3928 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003929 } else {
3930 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003931 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3932 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003933 }
John Kessenich6090df02016-06-30 21:18:02 -06003934 }
3935 }
3936
3937 // Make the SPIR-V type
3938 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003939 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003940 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3941
3942 // Decorate it
3943 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3944
John Kessenichd72f4882019-01-16 14:55:37 +07003945 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003946 auto it = deferredForwardPointers[i];
3947 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3948 }
3949
John Kessenich6090df02016-06-30 21:18:02 -06003950 return spvType;
3951}
3952
3953void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3954 const glslang::TTypeList* glslangMembers,
3955 glslang::TLayoutPacking explicitLayout,
3956 const glslang::TQualifier& qualifier,
3957 spv::Id spvType)
3958{
3959 // Name and decorate the non-hidden members
3960 int offset = -1;
3961 int locationOffset = 0; // for use within the members of this struct
Chow478b2322020-11-04 04:34:19 +08003962 bool memberLocationInvalid = type.isArrayOfArrays() ||
3963 (type.isArray() && (type.getQualifier().isArrayedIo(glslangIntermediate->getStage()) == false));
John Kessenich6090df02016-06-30 21:18:02 -06003964 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3965 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3966 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003967 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003968 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003969 if (filterMember(glslangMember))
3970 continue;
3971 }
John Kessenich6090df02016-06-30 21:18:02 -06003972
3973 // modify just this child's view of the qualifier
3974 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3975 InheritQualifiers(memberQualifier, qualifier);
3976
3977 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003978 if (member < 0)
3979 continue;
3980
3981 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3982 builder.addMemberDecoration(spvType, member,
3983 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3984 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3985 // Add interpolation and auxiliary storage decorations only to
3986 // top-level members of Input and Output storage classes
3987 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3988 type.getQualifier().storage == glslang::EvqVaryingOut) {
3989 if (type.getBasicType() == glslang::EbtBlock ||
3990 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3991 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3992 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003993#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003994 addMeshNVDecoration(spvType, member, memberQualifier);
3995#endif
John Kessenich6090df02016-06-30 21:18:02 -06003996 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003997 }
3998 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003999
John Kessenichb9197c82019-08-11 07:41:45 -06004000#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07004001 if (type.getBasicType() == glslang::EbtBlock &&
4002 qualifier.storage == glslang::EvqBuffer) {
4003 // Add memory decorations only to top-level members of shader storage block
4004 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05004005 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07004006 for (unsigned int i = 0; i < memory.size(); ++i)
4007 builder.addMemberDecoration(spvType, member, memory[i]);
4008 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004009
John Kessenichb9197c82019-08-11 07:41:45 -06004010#endif
John Kessenich6090df02016-06-30 21:18:02 -06004011
John Kessenich5d610ee2018-03-07 18:05:55 -07004012 // Location assignment was already completed correctly by the front end,
4013 // just track whether a member needs to be decorated.
4014 // Ignore member locations if the container is an array, as that's
4015 // ill-specified and decisions have been made to not allow this.
Chow478b2322020-11-04 04:34:19 +08004016 if (!memberLocationInvalid && memberQualifier.hasLocation())
John Kessenich5d610ee2018-03-07 18:05:55 -07004017 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004018
John Kessenich5d610ee2018-03-07 18:05:55 -07004019 if (qualifier.hasLocation()) // track for upcoming inheritance
4020 locationOffset += glslangIntermediate->computeTypeLocationSize(
4021 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004022
John Kessenich5d610ee2018-03-07 18:05:55 -07004023 // component, XFB, others
4024 if (glslangMember.getQualifier().hasComponent())
4025 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4026 glslangMember.getQualifier().layoutComponent);
4027 if (glslangMember.getQualifier().hasXfbOffset())
4028 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4029 glslangMember.getQualifier().layoutXfbOffset);
4030 else if (explicitLayout != glslang::ElpNone) {
4031 // figure out what to do with offset, which is accumulating
4032 int nextOffset;
4033 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4034 if (offset >= 0)
4035 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4036 offset = nextOffset;
4037 }
John Kessenich6090df02016-06-30 21:18:02 -06004038
John Kessenich5d610ee2018-03-07 18:05:55 -07004039 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4040 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4041 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004042
John Kessenich5d610ee2018-03-07 18:05:55 -07004043 // built-in variable decorations
4044 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4045 if (builtIn != spv::BuiltInMax)
4046 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004047
John Kessenichb9197c82019-08-11 07:41:45 -06004048#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004049 // nonuniform
4050 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4051
John Kessenichead86222018-03-28 18:01:20 -06004052 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4053 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4054 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4055 memberQualifier.semanticName);
4056 }
4057
John Kessenich5d610ee2018-03-07 18:05:55 -07004058 if (builtIn == spv::BuiltInLayer) {
4059 // SPV_NV_viewport_array2 extension
4060 if (glslangMember.getQualifier().layoutViewportRelative){
4061 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4062 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4063 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004064 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004065 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4066 builder.addMemberDecoration(spvType, member,
4067 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4068 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4069 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4070 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004071 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004072 }
4073 if (glslangMember.getQualifier().layoutPassthrough) {
4074 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4075 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4076 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4077 }
chaoc771d89f2017-01-13 01:10:53 -08004078#endif
John Kessenich6090df02016-06-30 21:18:02 -06004079 }
4080
4081 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004082 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4083 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004084}
4085
John Kessenich6c292d32016-02-15 20:58:50 -07004086// Turn the expression forming the array size into an id.
4087// This is not quite trivial, because of specialization constants.
4088// Sometimes, a raw constant is turned into an Id, and sometimes
4089// a specialization constant expression is.
4090spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4091{
4092 // First, see if this is sized with a node, meaning a specialization constant:
4093 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4094 if (specNode != nullptr) {
4095 builder.clearAccessChain();
4096 specNode->traverse(this);
4097 return accessChainLoad(specNode->getAsTyped()->getType());
4098 }
qining25262b32016-05-06 17:25:16 -04004099
John Kessenich6c292d32016-02-15 20:58:50 -07004100 // Otherwise, need a compile-time (front end) size, get it:
4101 int size = arraySizes.getDimSize(dim);
4102 assert(size > 0);
4103 return builder.makeUintConstant(size);
4104}
4105
John Kessenich103bef92016-02-08 21:38:15 -07004106// Wrap the builder's accessChainLoad to:
4107// - localize handling of RelaxedPrecision
4108// - use the SPIR-V inferred type instead of another conversion of the glslang type
4109// (avoids unnecessary work and possible type punning for structures)
4110// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004111spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4112{
John Kessenich103bef92016-02-08 21:38:15 -07004113 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004114
4115 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4116 coherentFlags |= TranslateCoherent(type);
4117
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004118 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004119 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004120
John Kessenich5611c6d2018-04-05 11:25:02 -06004121 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004122 TranslateNonUniformDecoration(type.getQualifier()),
4123 nominalTypeId,
4124 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4125 TranslateMemoryScope(coherentFlags),
4126 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004127
4128 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004129 if (type.getBasicType() == glslang::EbtBool) {
4130 if (builder.isScalarType(nominalTypeId)) {
4131 // Conversion for bool
4132 spv::Id boolType = builder.makeBoolType();
4133 if (nominalTypeId != boolType)
4134 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4135 } else if (builder.isVectorType(nominalTypeId)) {
4136 // Conversion for bvec
4137 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4138 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4139 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004140 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4141 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004142 }
4143 }
John Kessenich103bef92016-02-08 21:38:15 -07004144
4145 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004146}
4147
Rex Xu27253232016-02-23 17:51:09 +08004148// Wrap the builder's accessChainStore to:
4149// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004150//
4151// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004152void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4153{
4154 // Need to convert to abstract types when necessary
4155 if (type.getBasicType() == glslang::EbtBool) {
4156 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4157
4158 if (builder.isScalarType(nominalTypeId)) {
4159 // Conversion for bool
4160 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004161 if (nominalTypeId != boolType) {
4162 // keep these outside arguments, for determinant order-of-evaluation
4163 spv::Id one = builder.makeUintConstant(1);
4164 spv::Id zero = builder.makeUintConstant(0);
4165 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4166 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004167 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004168 } else if (builder.isVectorType(nominalTypeId)) {
4169 // Conversion for bvec
4170 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4171 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004172 if (nominalTypeId != bvecType) {
4173 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004174 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4175 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4176 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004177 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004178 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4179 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004180 }
4181 }
4182
Jeff Bolz36831c92018-09-05 10:11:41 -05004183 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4184 coherentFlags |= TranslateCoherent(type);
4185
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004186 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004187 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004188
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02004189 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(type.getQualifier()),
John Kessenich8985fc92020-03-03 10:25:07 -07004190 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4191 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004192 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004193}
4194
John Kessenich4bf71552016-09-02 11:20:21 -06004195// For storing when types match at the glslang level, but not might match at the
4196// SPIR-V level.
4197//
4198// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004199// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004200// as in a member-decorated way.
4201//
4202// NOTE: This function can handle any store request; if it's not special it
4203// simplifies to a simple OpStore.
4204//
4205// Implicitly uses the existing builder.accessChain as the storage target.
4206void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4207{
John Kessenichb3e24e42016-09-11 12:33:43 -06004208 // we only do the complex path here if it's an aggregate
4209 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004210 accessChainStore(type, rValue);
4211 return;
4212 }
4213
John Kessenichb3e24e42016-09-11 12:33:43 -06004214 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004215 spv::Id rType = builder.getTypeId(rValue);
4216 spv::Id lValue = builder.accessChainGetLValue();
4217 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4218 if (lType == rType) {
4219 accessChainStore(type, rValue);
4220 return;
4221 }
4222
John Kessenichb3e24e42016-09-11 12:33:43 -06004223 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004224 // where the two types were the same type in GLSL. This requires member
4225 // by member copy, recursively.
4226
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004227 // SPIR-V 1.4 added an instruction to do help do this.
4228 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4229 // However, bool in uniform space is changed to int, so
4230 // OpCopyLogical does not work for that.
4231 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4232 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4233 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4234 if (lBool == rBool) {
4235 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4236 accessChainStore(type, logicalCopy);
4237 return;
4238 }
4239 }
4240
John Kessenichb3e24e42016-09-11 12:33:43 -06004241 // If an array, copy element by element.
4242 if (type.isArray()) {
4243 glslang::TType glslangElementType(type, 0);
4244 spv::Id elementRType = builder.getContainedTypeId(rType);
4245 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4246 // get the source member
4247 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004248
John Kessenichb3e24e42016-09-11 12:33:43 -06004249 // set up the target storage
4250 builder.clearAccessChain();
4251 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004252 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4253 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004254
John Kessenichb3e24e42016-09-11 12:33:43 -06004255 // store the member
4256 multiTypeStore(glslangElementType, elementRValue);
4257 }
4258 } else {
4259 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004260
John Kessenichb3e24e42016-09-11 12:33:43 -06004261 // loop over structure members
4262 const glslang::TTypeList& members = *type.getStruct();
4263 for (int m = 0; m < (int)members.size(); ++m) {
4264 const glslang::TType& glslangMemberType = *members[m].type;
4265
4266 // get the source member
4267 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4268 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4269
4270 // set up the target storage
4271 builder.clearAccessChain();
4272 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004273 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4274 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004275
4276 // store the member
4277 multiTypeStore(glslangMemberType, memberRValue);
4278 }
John Kessenich4bf71552016-09-02 11:20:21 -06004279 }
4280}
4281
John Kessenichf85e8062015-12-19 13:57:10 -07004282// Decide whether or not this type should be
4283// decorated with offsets and strides, and if so
4284// whether std140 or std430 rules should be applied.
4285glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004286{
John Kessenichf85e8062015-12-19 13:57:10 -07004287 // has to be a block
4288 if (type.getBasicType() != glslang::EbtBlock)
4289 return glslang::ElpNone;
4290
Chao Chen3c366992018-09-19 11:41:59 -07004291 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004292 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004293 type.getQualifier().storage != glslang::EvqBuffer &&
4294 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004295 return glslang::ElpNone;
4296
4297 // return the layout to use
4298 switch (type.getQualifier().layoutPacking) {
4299 case glslang::ElpStd140:
4300 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004301 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004302 return type.getQualifier().layoutPacking;
4303 default:
4304 return glslang::ElpNone;
4305 }
John Kessenich31ed4832015-09-09 17:51:38 -06004306}
4307
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004308// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004309int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4310 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004311{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004312 int size;
John Kessenich49987892015-12-29 17:11:44 -07004313 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004314 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4315 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004316
4317 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004318}
4319
John Kessenich49987892015-12-29 17:11:44 -07004320// 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 -07004321// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004322int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4323 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004324{
John Kessenich49987892015-12-29 17:11:44 -07004325 glslang::TType elementType;
4326 elementType.shallowCopy(matrixType);
4327 elementType.clearArraySizes();
4328
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004329 int size;
John Kessenich49987892015-12-29 17:11:44 -07004330 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004331 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4332 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004333
4334 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004335}
4336
John Kessenich5e4b1242015-08-06 22:53:06 -06004337// Given a member type of a struct, realign the current offset for it, and compute
4338// the next (not yet aligned) offset for the next member, which will get aligned
4339// on the next call.
4340// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4341// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4342// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004343void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4344 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004345{
4346 // this will get a positive value when deemed necessary
4347 nextOffset = -1;
4348
John Kessenich5e4b1242015-08-06 22:53:06 -06004349 // override anything in currentOffset with user-set offset
4350 if (memberType.getQualifier().hasOffset())
4351 currentOffset = memberType.getQualifier().layoutOffset;
4352
4353 // It could be that current linker usage in glslang updated all the layoutOffset,
4354 // in which case the following code does not matter. But, that's not quite right
4355 // once cross-compilation unit GLSL validation is done, as the original user
4356 // settings are needed in layoutOffset, and then the following will come into play.
4357
John Kessenichf85e8062015-12-19 13:57:10 -07004358 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004359 if (! memberType.getQualifier().hasOffset())
4360 currentOffset = -1;
4361
4362 return;
4363 }
4364
John Kessenichf85e8062015-12-19 13:57:10 -07004365 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004366 if (currentOffset < 0)
4367 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004368
John Kessenich5e4b1242015-08-06 22:53:06 -06004369 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4370 // but possibly not yet correctly aligned.
4371
4372 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004373 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004374 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4375 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004376
4377 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004378 // TODO: make this consistent in early phases of code:
4379 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4380 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4381 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004382 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004383 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004384 int dummySize;
4385 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4386 if (componentAlignment <= 4)
4387 memberAlignment = componentAlignment;
4388 }
4389
4390 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004391 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004392
4393 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004394 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4395 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004396 glslang::RoundToPow2(currentOffset, 16);
4397
John Kessenich5e4b1242015-08-06 22:53:06 -06004398 nextOffset = currentOffset + memberSize;
4399}
4400
David Netoa901ffe2016-06-08 14:11:40 +01004401void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004402{
David Netoa901ffe2016-06-08 14:11:40 +01004403 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4404 switch (glslangBuiltIn)
4405 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004406 case glslang::EbvPointSize:
4407#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004408 case glslang::EbvClipDistance:
4409 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004410 case glslang::EbvViewportMaskNV:
4411 case glslang::EbvSecondaryPositionNV:
4412 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004413 case glslang::EbvPositionPerViewNV:
4414 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004415 case glslang::EbvTaskCountNV:
4416 case glslang::EbvPrimitiveCountNV:
4417 case glslang::EbvPrimitiveIndicesNV:
4418 case glslang::EbvClipDistancePerViewNV:
4419 case glslang::EbvCullDistancePerViewNV:
4420 case glslang::EbvLayerPerViewNV:
4421 case glslang::EbvMeshViewCountNV:
4422 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004423#endif
David Netoa901ffe2016-06-08 14:11:40 +01004424 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4425 // Alternately, we could just call this for any glslang built-in, since the
4426 // capability already guards against duplicates.
4427 TranslateBuiltInDecoration(glslangBuiltIn, false);
4428 break;
4429 default:
4430 // Capabilities were already generated when the struct was declared.
4431 break;
4432 }
John Kessenichebb50532016-05-16 19:22:05 -06004433}
4434
John Kessenich6fccb3c2016-09-19 16:01:41 -06004435bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004436{
John Kessenicheee9d532016-09-19 18:09:30 -06004437 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004438}
4439
John Kessenichd41993d2017-09-10 15:21:05 -06004440// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004441// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4442// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004443bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004444{
John Kessenich6a14f782017-12-04 02:48:10 -07004445 assert(qualifier == glslang::EvqIn ||
4446 qualifier == glslang::EvqOut ||
4447 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004448 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004449 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004450 return qualifier != glslang::EvqConstReadOnly &&
4451 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004452}
4453
4454// Is parameter pass-by-original?
4455bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4456 bool implicitThisParam)
4457{
4458 if (implicitThisParam) // implicit this
4459 return true;
4460 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004461 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004462 return paramType.containsOpaque() || // sampler, etc.
4463 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4464}
4465
John Kessenich140f3df2015-06-26 16:58:36 -06004466// Make all the functions, skeletally, without actually visiting their bodies.
4467void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4468{
John Kessenich8985fc92020-03-03 10:25:07 -07004469 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4470 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004471 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4472 if (paramPrecision != spv::NoPrecision)
4473 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004474 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004475 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004476 // Original and non-writable params pass the pointer directly and
4477 // use restrict/aliased, others are stored to a pointer in Function
4478 // memory and use RestrictPointer/AliasedPointer.
4479 if (originalParam(type.getQualifier().storage, type, false) ||
4480 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004481 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4482 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004483 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004484 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4485 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004486 }
4487 }
John Kessenichfad62972017-07-18 02:35:46 -06004488 };
4489
John Kessenich140f3df2015-06-26 16:58:36 -06004490 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4491 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004492 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004493 continue;
4494
4495 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004496 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004497 //
qining25262b32016-05-06 17:25:16 -04004498 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004499 // function. What it is an address of varies:
4500 //
John Kessenich4bf71552016-09-02 11:20:21 -06004501 // - "in" parameters not marked as "const" can be written to without modifying the calling
4502 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004503 //
4504 // - "const in" parameters can just be the r-value, as no writes need occur.
4505 //
John Kessenich4bf71552016-09-02 11:20:21 -06004506 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4507 // 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 -06004508
4509 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004510 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004511 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4512
John Kessenich155d3512019-08-08 23:29:20 -06004513#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004514 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4515 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004516#else
4517 bool implicitThis = false;
4518#endif
John Kessenich37789792017-03-21 23:56:40 -06004519
John Kessenichfad62972017-07-18 02:35:46 -06004520 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004521 for (int p = 0; p < (int)parameters.size(); ++p) {
4522 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4523 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004524 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004525 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004526 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004527 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4528 else
John Kessenich4bf71552016-09-02 11:20:21 -06004529 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004530 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004531 paramTypes.push_back(typeId);
4532 }
4533
4534 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004535 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4536 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004537 glslFunction->getName().c_str(), paramTypes,
4538 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004539 if (implicitThis)
4540 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004541
4542 // Track function to emit/call later
4543 functionMap[glslFunction->getName().c_str()] = function;
4544
4545 // Set the parameter id's
4546 for (int p = 0; p < (int)parameters.size(); ++p) {
4547 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4548 // give a name too
4549 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004550
4551 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004552 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004553 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004554 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004555 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004556 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004557 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004558 }
4559 }
4560}
4561
4562// Process all the initializers, while skipping the functions and link objects
4563void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4564{
4565 builder.setBuildPoint(shaderEntry->getLastBlock());
4566 for (int i = 0; i < (int)initializers.size(); ++i) {
4567 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004568 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4569 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004570
4571 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004572 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004573 initializer->traverse(this);
4574 }
4575 }
4576}
4577
4578// Process all the functions, while skipping initializers.
4579void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4580{
4581 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4582 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004583 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004584 node->traverse(this);
4585 }
4586}
4587
4588void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4589{
qining25262b32016-05-06 17:25:16 -04004590 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004591 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004592 currentFunction = functionMap[node->getName().c_str()];
4593 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004594 builder.setBuildPoint(functionBlock);
4595}
4596
John Kessenich8985fc92020-03-03 10:25:07 -07004597void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4598 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004599{
Rex Xufc618912015-09-09 16:42:49 +08004600 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004601
4602 glslang::TSampler sampler = {};
4603 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004604#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004605 bool f16ShadowCompare = false;
4606#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004607 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004608 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4609 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004610#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004611 f16ShadowCompare = sampler.shadow &&
4612 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004613#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004614 }
4615
John Kessenich140f3df2015-06-26 16:58:36 -06004616 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4617 builder.clearAccessChain();
4618 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004619
John Kessenicha28f7a72019-08-06 07:00:58 -06004620#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004621 // Special case l-value operands
4622 bool lvalue = false;
4623 switch (node.getOp()) {
4624 case glslang::EOpImageAtomicAdd:
4625 case glslang::EOpImageAtomicMin:
4626 case glslang::EOpImageAtomicMax:
4627 case glslang::EOpImageAtomicAnd:
4628 case glslang::EOpImageAtomicOr:
4629 case glslang::EOpImageAtomicXor:
4630 case glslang::EOpImageAtomicExchange:
4631 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004632 case glslang::EOpImageAtomicLoad:
4633 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004634 if (i == 0)
4635 lvalue = true;
4636 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004637 case glslang::EOpSparseImageLoad:
4638 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4639 lvalue = true;
4640 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004641 case glslang::EOpSparseTexture:
4642 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4643 lvalue = true;
4644 break;
4645 case glslang::EOpSparseTextureClamp:
4646 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4647 lvalue = true;
4648 break;
4649 case glslang::EOpSparseTextureLod:
4650 case glslang::EOpSparseTextureOffset:
4651 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4652 lvalue = true;
4653 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004654 case glslang::EOpSparseTextureFetch:
4655 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4656 lvalue = true;
4657 break;
4658 case glslang::EOpSparseTextureFetchOffset:
4659 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4660 lvalue = true;
4661 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004662 case glslang::EOpSparseTextureLodOffset:
4663 case glslang::EOpSparseTextureGrad:
4664 case glslang::EOpSparseTextureOffsetClamp:
4665 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4666 lvalue = true;
4667 break;
4668 case glslang::EOpSparseTextureGradOffset:
4669 case glslang::EOpSparseTextureGradClamp:
4670 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4671 lvalue = true;
4672 break;
4673 case glslang::EOpSparseTextureGradOffsetClamp:
4674 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4675 lvalue = true;
4676 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004677 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004678 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4679 lvalue = true;
4680 break;
4681 case glslang::EOpSparseTextureGatherOffset:
4682 case glslang::EOpSparseTextureGatherOffsets:
4683 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4684 lvalue = true;
4685 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004686 case glslang::EOpSparseTextureGatherLod:
4687 if (i == 3)
4688 lvalue = true;
4689 break;
4690 case glslang::EOpSparseTextureGatherLodOffset:
4691 case glslang::EOpSparseTextureGatherLodOffsets:
4692 if (i == 4)
4693 lvalue = true;
4694 break;
Rex Xu129799a2017-07-05 17:23:28 +08004695 case glslang::EOpSparseImageLoadLod:
4696 if (i == 3)
4697 lvalue = true;
4698 break;
Chao Chen3a137962018-09-19 11:41:27 -07004699 case glslang::EOpImageSampleFootprintNV:
4700 if (i == 4)
4701 lvalue = true;
4702 break;
4703 case glslang::EOpImageSampleFootprintClampNV:
4704 case glslang::EOpImageSampleFootprintLodNV:
4705 if (i == 5)
4706 lvalue = true;
4707 break;
4708 case glslang::EOpImageSampleFootprintGradNV:
4709 if (i == 6)
4710 lvalue = true;
4711 break;
4712 case glslang::EOpImageSampleFootprintGradClampNV:
4713 if (i == 7)
4714 lvalue = true;
4715 break;
Rex Xufc618912015-09-09 16:42:49 +08004716 default:
4717 break;
4718 }
4719
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004720 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004721 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004722 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4723 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4724 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004725#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004726 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004727 }
4728}
4729
John Kessenichfc51d282015-08-19 13:34:18 -06004730void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004731{
John Kessenichfc51d282015-08-19 13:34:18 -06004732 builder.clearAccessChain();
4733 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004734 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004735}
John Kessenich140f3df2015-06-26 16:58:36 -06004736
John Kessenichfc51d282015-08-19 13:34:18 -06004737spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4738{
John Kesseniche485c7a2017-05-31 18:50:53 -06004739 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004740 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004741
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004742 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004743
John Kessenichfc51d282015-08-19 13:34:18 -06004744 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004745
John Kessenichf43c7392019-03-31 10:51:57 -06004746 const glslang::TType &imageType = node->getAsAggregate()
4747 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4748 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004749 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004750#ifdef GLSLANG_WEB
4751 const bool f16ShadowCompare = false;
4752#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004753 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004754 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4755 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004756#endif
4757
John Kessenichf43c7392019-03-31 10:51:57 -06004758 const auto signExtensionMask = [&]() {
4759 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4760 if (sampler.type == glslang::EbtUint)
4761 return spv::ImageOperandsZeroExtendMask;
4762 else if (sampler.type == glslang::EbtInt)
4763 return spv::ImageOperandsSignExtendMask;
4764 }
4765 return spv::ImageOperandsMaskNone;
4766 };
4767
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004768 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4769
John Kessenichfc51d282015-08-19 13:34:18 -06004770 std::vector<spv::Id> arguments;
4771 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004772 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004773 else
4774 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004775 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004776
4777 spv::Builder::TextureParameters params = { };
4778 params.sampler = arguments[0];
4779
Rex Xu04db3f52015-09-16 11:44:02 +08004780 glslang::TCrackedTextureOp cracked;
4781 node->crackTexture(sampler, cracked);
4782
amhagan05506bb2017-06-13 16:53:02 -04004783 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004784
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004785 if (builder.isSampledImage(params.sampler) &&
4786 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4787 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4788 if (imageType.getQualifier().isNonUniform()) {
4789 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4790 }
4791 }
John Kessenichfc51d282015-08-19 13:34:18 -06004792 // Check for queries
4793 if (cracked.query) {
4794 switch (node->getOp()) {
4795 case glslang::EOpImageQuerySize:
4796 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004797 if (arguments.size() > 1) {
4798 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004799 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004800 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004801 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004802#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004803 case glslang::EOpImageQuerySamples:
4804 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004805 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004806 case glslang::EOpTextureQueryLod:
4807 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004808 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004809 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004810 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004811 case glslang::EOpSparseTexelsResident:
4812 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004813#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004814 default:
4815 assert(0);
4816 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004817 }
John Kessenich140f3df2015-06-26 16:58:36 -06004818 }
4819
LoopDawg4425f242018-02-18 11:40:01 -07004820 int components = node->getType().getVectorSize();
4821
4822 if (node->getOp() == glslang::EOpTextureFetch) {
4823 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4824 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4825 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4826 // here around e.g. which ones return scalars or other types.
4827 components = 4;
4828 }
4829
4830 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4831
4832 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4833
Rex Xufc618912015-09-09 16:42:49 +08004834 // Check for image functions other than queries
4835 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004836 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004837 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004838 spv::IdImmediate image = { true, *(opIt++) };
4839 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004840
4841 // Handle subpass operations
4842 // TODO: GLSL should change to have the "MS" only on the type rather than the
4843 // built-in function.
4844 if (cracked.subpass) {
4845 // add on the (0,0) coordinate
4846 spv::Id zero = builder.makeIntConstant(0);
4847 std::vector<spv::Id> comps;
4848 comps.push_back(zero);
4849 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004850 spv::IdImmediate coord = { true,
4851 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4852 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004853 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4854 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004855 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004856 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4857 }
4858 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004859 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004860 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004861 spv::IdImmediate imageOperand = { true, *(opIt++) };
4862 operands.push_back(imageOperand);
4863 }
John Kessenich6c292d32016-02-15 20:58:50 -07004864 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004865 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4866 builder.setPrecision(result, precision);
4867 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004868 }
4869
John Kessenich149afc32018-08-14 13:31:43 -06004870 spv::IdImmediate coord = { true, *(opIt++) };
4871 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004872 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004873 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004874 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004875 mask = mask | spv::ImageOperandsSampleMask;
4876 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004877 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004878 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4879 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004880 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004881 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004882 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4883 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004884 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004885 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004886 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4887 operands.push_back(imageOperands);
4888 }
4889 if (mask & spv::ImageOperandsSampleMask) {
4890 spv::IdImmediate imageOperand = { true, *opIt++ };
4891 operands.push_back(imageOperand);
4892 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004893 if (mask & spv::ImageOperandsLodMask) {
4894 spv::IdImmediate imageOperand = { true, *opIt++ };
4895 operands.push_back(imageOperand);
4896 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004897 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004898 spv::IdImmediate imageOperand = { true,
4899 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004900 operands.push_back(imageOperand);
4901 }
4902
John Kessenich149afc32018-08-14 13:31:43 -06004903 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004904 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004905
John Kessenich149afc32018-08-14 13:31:43 -06004906 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004907 builder.setPrecision(result[0], precision);
4908
4909 // If needed, add a conversion constructor to the proper size.
4910 if (components != node->getType().getVectorSize())
4911 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4912
4913 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004914 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004915
Jeff Bolz36831c92018-09-05 10:11:41 -05004916 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004917 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004918 spv::IdImmediate texel = { true, *(opIt + 1) };
4919 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004920 } else {
4921 spv::IdImmediate texel = { true, *opIt };
4922 operands.push_back(texel);
4923 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004924
4925 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004926 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004927 mask = mask | spv::ImageOperandsSampleMask;
4928 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004929 if (cracked.lod) {
4930 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4931 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4932 mask = mask | spv::ImageOperandsLodMask;
4933 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004934 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4935 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004936 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004937 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004938 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4939 operands.push_back(imageOperands);
4940 }
4941 if (mask & spv::ImageOperandsSampleMask) {
4942 spv::IdImmediate imageOperand = { true, *opIt++ };
4943 operands.push_back(imageOperand);
4944 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004945 if (mask & spv::ImageOperandsLodMask) {
4946 spv::IdImmediate imageOperand = { true, *opIt++ };
4947 operands.push_back(imageOperand);
4948 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004949 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004950 spv::IdImmediate imageOperand = { true,
4951 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004952 operands.push_back(imageOperand);
4953 }
4954
John Kessenich56bab042015-09-16 10:54:31 -06004955 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004956 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004957 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004958 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004959 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4960 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004961 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004962 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004963 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4964
Jeff Bolz36831c92018-09-05 10:11:41 -05004965 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004966 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004967 mask = mask | spv::ImageOperandsSampleMask;
4968 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004969 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004970 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4971 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4972
Jeff Bolz36831c92018-09-05 10:11:41 -05004973 mask = mask | spv::ImageOperandsLodMask;
4974 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004975 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4976 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004977 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004978 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004979 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004980 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004981 }
4982 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004983 spv::IdImmediate imageOperand = { true, *opIt++ };
4984 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004985 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004986 if (mask & spv::ImageOperandsLodMask) {
4987 spv::IdImmediate imageOperand = { true, *opIt++ };
4988 operands.push_back(imageOperand);
4989 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004990 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004991 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4992 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004993 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004994 }
4995
4996 // Create the return type that was a special structure
4997 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004998 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004999 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
5000 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
5001
5002 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
5003
5004 // Decode the return type
5005 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
5006 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07005007 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08005008 // Process image atomic operations
5009
5010 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5011 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005012 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005013 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005014 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005015
Jeff Bolz36831c92018-09-05 10:11:41 -05005016 spv::Id resultTypeId;
5017 // imageAtomicStore has a void return type so base the pointer type on
5018 // the type of the value operand.
5019 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005020 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005021 } else {
5022 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5023 }
John Kessenich56bab042015-09-16 10:54:31 -06005024 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005025 if (imageType.getQualifier().nonUniform) {
5026 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5027 }
Rex Xufc618912015-09-09 16:42:49 +08005028
5029 std::vector<spv::Id> operands;
5030 operands.push_back(pointer);
5031 for (; opIt != arguments.end(); ++opIt)
5032 operands.push_back(*opIt);
5033
John Kessenich8985fc92020-03-03 10:25:07 -07005034 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5035 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005036 }
5037 }
5038
John Kessenicha28f7a72019-08-06 07:00:58 -06005039#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005040 // Check for fragment mask functions other than queries
5041 if (cracked.fragMask) {
5042 assert(sampler.ms);
5043
5044 auto opIt = arguments.begin();
5045 std::vector<spv::Id> operands;
5046
amhagan05506bb2017-06-13 16:53:02 -04005047 operands.push_back(params.sampler);
5048 ++opIt;
5049
5050 if (sampler.isSubpass()) {
5051 // add on the (0,0) coordinate
5052 spv::Id zero = builder.makeIntConstant(0);
5053 std::vector<spv::Id> comps;
5054 comps.push_back(zero);
5055 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005056 operands.push_back(builder.makeCompositeConstant(
5057 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005058 }
5059
5060 for (; opIt != arguments.end(); ++opIt)
5061 operands.push_back(*opIt);
5062
5063 spv::Op fragMaskOp = spv::OpNop;
5064 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5065 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5066 else if (node->getOp() == glslang::EOpFragmentFetch)
5067 fragMaskOp = spv::OpFragmentFetchAMD;
5068
5069 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5070 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5071 return builder.createOp(fragMaskOp, resultType(), operands);
5072 }
5073#endif
5074
Rex Xufc618912015-09-09 16:42:49 +08005075 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005076 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005077 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005078 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005079
John Kessenichfc51d282015-08-19 13:34:18 -06005080 // check for bias argument
5081 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005082 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005083 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005084 if (cracked.gather)
5085 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005086
5087 if (f16ShadowCompare)
5088 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005089 if (cracked.offset)
5090 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005091 else if (cracked.offsets)
5092 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005093 if (cracked.grad)
5094 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005095 if (cracked.lodClamp)
5096 ++nonBiasArgCount;
5097 if (sparse)
5098 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005099 if (imageFootprint)
5100 //Following three extra arguments
5101 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5102 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005103 if ((int)arguments.size() > nonBiasArgCount)
5104 bias = true;
5105 }
5106
John Kessenicha28f7a72019-08-06 07:00:58 -06005107#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005108 if (cracked.gather) {
5109 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5110 if (bias || cracked.lod ||
5111 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5112 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005113 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005114 }
5115 }
5116#endif
5117
John Kessenichfc51d282015-08-19 13:34:18 -06005118 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005119
John Kessenichfc51d282015-08-19 13:34:18 -06005120 params.coords = arguments[1];
5121 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005122 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005123
5124 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005125 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005126 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005127 ++extraArgs;
5128 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005129 params.Dref = arguments[2];
5130 ++extraArgs;
5131 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005132 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005133 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005134 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005135 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005136 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005137 dRefComp = builder.getNumComponents(params.coords) - 1;
5138 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005139 params.Dref = builder.createCompositeExtract(params.coords,
5140 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005141 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005142
5143 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005144 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005145 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005146 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005147 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5148 !(glslangIntermediate->getStage() == EShLangCompute &&
5149 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005150 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5151 noImplicitLod = true;
5152 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005153
5154 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005155 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005156 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005157 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005158 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005159
5160 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005161 if (cracked.grad) {
5162 params.gradX = arguments[2 + extraArgs];
5163 params.gradY = arguments[3 + extraArgs];
5164 extraArgs += 2;
5165 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005166
5167 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005168 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005169 params.offset = arguments[2 + extraArgs];
5170 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005171 } else if (cracked.offsets) {
5172 params.offsets = arguments[2 + extraArgs];
5173 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005174 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005175
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005176#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005177 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005178 if (cracked.lodClamp) {
5179 params.lodClamp = arguments[2 + extraArgs];
5180 ++extraArgs;
5181 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005182 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005183 if (sparse) {
5184 params.texelOut = arguments[2 + extraArgs];
5185 ++extraArgs;
5186 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005187 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005188 if (cracked.gather && ! sampler.shadow) {
5189 // default component is 0, if missing, otherwise an argument
5190 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005191 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005192 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005193 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005194 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005195 }
Chao Chen3a137962018-09-19 11:41:27 -07005196 spv::Id resultStruct = spv::NoResult;
5197 if (imageFootprint) {
5198 //Following three extra arguments
5199 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5200 params.granularity = arguments[2 + extraArgs];
5201 params.coarse = arguments[3 + extraArgs];
5202 resultStruct = arguments[4 + extraArgs];
5203 extraArgs += 3;
5204 }
5205#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005206 // bias
5207 if (bias) {
5208 params.bias = arguments[2 + extraArgs];
5209 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005210 }
John Kessenichfc51d282015-08-19 13:34:18 -06005211
John Kessenicha28f7a72019-08-06 07:00:58 -06005212#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005213 if (imageFootprint) {
5214 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5215 builder.addCapability(spv::CapabilityImageFootprintNV);
5216
5217
5218 //resultStructType(OpenGL type) contains 5 elements:
5219 //struct gl_TextureFootprint2DNV {
5220 // uvec2 anchor;
5221 // uvec2 offset;
5222 // uvec2 mask;
5223 // uint lod;
5224 // uint granularity;
5225 //};
5226 //or
5227 //struct gl_TextureFootprint3DNV {
5228 // uvec3 anchor;
5229 // uvec3 offset;
5230 // uvec2 mask;
5231 // uint lod;
5232 // uint granularity;
5233 //};
5234 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5235 assert(builder.isStructType(resultStructType));
5236
5237 //resType (SPIR-V type) contains 6 elements:
5238 //Member 0 must be a Boolean type scalar(LOD),
5239 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5240 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5241 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5242 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5243 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5244 std::vector<spv::Id> members;
5245 members.push_back(resultType());
5246 for (int i = 0; i < 5; i++) {
5247 members.push_back(builder.getContainedTypeId(resultStructType, i));
5248 }
5249 spv::Id resType = builder.makeStructType(members, "ResType");
5250
5251 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005252 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5253 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005254
5255 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5256 for (int i = 0; i < 5; i++) {
5257 builder.clearAccessChain();
5258 builder.setAccessChainLValue(resultStruct);
5259
5260 //Accessing to a struct we created, no coherent flag is set
5261 spv::Builder::AccessChain::CoherentFlags flags;
5262 flags.clear();
5263
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005264 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005265 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005266 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005267 }
5268 return builder.createCompositeExtract(res, resultType(), 0);
5269 }
5270#endif
5271
John Kessenich65336482016-06-16 14:06:26 -06005272 // projective component (might not to move)
5273 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5274 // are divided by the last component of P."
5275 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5276 // unused components will appear after all used components."
5277 if (cracked.proj) {
5278 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5279 int projTargetComp;
5280 switch (sampler.dim) {
5281 case glslang::Esd1D: projTargetComp = 1; break;
5282 case glslang::Esd2D: projTargetComp = 2; break;
5283 case glslang::EsdRect: projTargetComp = 2; break;
5284 default: projTargetComp = projSourceComp; break;
5285 }
5286 // copy the projective coordinate if we have to
5287 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005288 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005289 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005290 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005291 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005292 }
5293 }
5294
John Kessenichf8d1d742019-10-21 06:55:11 -06005295#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005296 // nonprivate
5297 if (imageType.getQualifier().nonprivate) {
5298 params.nonprivate = true;
5299 }
5300
5301 // volatile
5302 if (imageType.getQualifier().volatil) {
5303 params.volatil = true;
5304 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005305#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005306
St0fFa1184dd2018-04-09 21:08:14 +02005307 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005308 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5309 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005310 );
LoopDawg4425f242018-02-18 11:40:01 -07005311
5312 if (components != node->getType().getVectorSize())
5313 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5314
5315 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005316}
5317
5318spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5319{
5320 // Grab the function's pointer from the previously created function
5321 spv::Function* function = functionMap[node->getName().c_str()];
5322 if (! function)
5323 return 0;
5324
5325 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5326 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5327
5328 // See comments in makeFunctions() for details about the semantics for parameter passing.
5329 //
5330 // These imply we need a four step process:
5331 // 1. Evaluate the arguments
5332 // 2. Allocate and make copies of in, out, and inout arguments
5333 // 3. Make the call
5334 // 4. Copy back the results
5335
John Kessenichd3ed90b2018-05-04 11:43:03 -06005336 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005337 std::vector<spv::Builder::AccessChain> lValues;
5338 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005339 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005340 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005341 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005342 // build l-value
5343 builder.clearAccessChain();
5344 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005345 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005346 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005347 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005348 // save l-value
5349 lValues.push_back(builder.getAccessChain());
5350 } else {
5351 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005352 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005353 }
5354 }
5355
5356 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5357 // copy the original into that space.
5358 //
5359 // Also, build up the list of actual arguments to pass in for the call
5360 int lValueCount = 0;
5361 int rValueCount = 0;
5362 std::vector<spv::Id> spvArgs;
5363 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5364 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005365 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005366 builder.setAccessChain(lValues[lValueCount]);
5367 arg = builder.accessChainGetLValue();
5368 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005369 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005370 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005371 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005372 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005373 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5374 // need to copy the input into output space
5375 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005376 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005377 builder.clearAccessChain();
5378 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005379 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005380 }
5381 ++lValueCount;
5382 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005383 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005384 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005385 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005386 {
John Kessenich435dd802020-06-30 01:27:08 -06005387 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005388 builder.clearAccessChain();
5389 builder.setAccessChainLValue(argCopy);
5390 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005391 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005392 } else
5393 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005394 ++rValueCount;
5395 }
5396 spvArgs.push_back(arg);
5397 }
5398
5399 // 3. Make the call.
5400 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005401 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005402
5403 // 4. Copy back out an "out" arguments.
5404 lValueCount = 0;
5405 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005406 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005407 ++lValueCount;
5408 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005409 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005410 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005411 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005412 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005413 }
5414 ++lValueCount;
5415 }
5416 }
5417
5418 return result;
5419}
5420
5421// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005422spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005423 spv::Id typeId, spv::Id left, spv::Id right,
5424 glslang::TBasicType typeProxy, bool reduceComparison)
5425{
John Kessenich66011cb2018-03-06 16:12:04 -07005426 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5427 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005428 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005429
5430 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005431 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005432 bool comparison = false;
5433
5434 switch (op) {
5435 case glslang::EOpAdd:
5436 case glslang::EOpAddAssign:
5437 if (isFloat)
5438 binOp = spv::OpFAdd;
5439 else
5440 binOp = spv::OpIAdd;
5441 break;
5442 case glslang::EOpSub:
5443 case glslang::EOpSubAssign:
5444 if (isFloat)
5445 binOp = spv::OpFSub;
5446 else
5447 binOp = spv::OpISub;
5448 break;
5449 case glslang::EOpMul:
5450 case glslang::EOpMulAssign:
5451 if (isFloat)
5452 binOp = spv::OpFMul;
5453 else
5454 binOp = spv::OpIMul;
5455 break;
5456 case glslang::EOpVectorTimesScalar:
5457 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005458 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005459 if (builder.isVector(right))
5460 std::swap(left, right);
5461 assert(builder.isScalar(right));
5462 needMatchingVectors = false;
5463 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005464 } else if (isFloat)
5465 binOp = spv::OpFMul;
5466 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005467 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005468 break;
5469 case glslang::EOpVectorTimesMatrix:
5470 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005471 binOp = spv::OpVectorTimesMatrix;
5472 break;
5473 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005474 binOp = spv::OpMatrixTimesVector;
5475 break;
5476 case glslang::EOpMatrixTimesScalar:
5477 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005478 binOp = spv::OpMatrixTimesScalar;
5479 break;
5480 case glslang::EOpMatrixTimesMatrix:
5481 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005482 binOp = spv::OpMatrixTimesMatrix;
5483 break;
5484 case glslang::EOpOuterProduct:
5485 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005486 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005487 break;
5488
5489 case glslang::EOpDiv:
5490 case glslang::EOpDivAssign:
5491 if (isFloat)
5492 binOp = spv::OpFDiv;
5493 else if (isUnsigned)
5494 binOp = spv::OpUDiv;
5495 else
5496 binOp = spv::OpSDiv;
5497 break;
5498 case glslang::EOpMod:
5499 case glslang::EOpModAssign:
5500 if (isFloat)
5501 binOp = spv::OpFMod;
5502 else if (isUnsigned)
5503 binOp = spv::OpUMod;
5504 else
5505 binOp = spv::OpSMod;
5506 break;
5507 case glslang::EOpRightShift:
5508 case glslang::EOpRightShiftAssign:
5509 if (isUnsigned)
5510 binOp = spv::OpShiftRightLogical;
5511 else
5512 binOp = spv::OpShiftRightArithmetic;
5513 break;
5514 case glslang::EOpLeftShift:
5515 case glslang::EOpLeftShiftAssign:
5516 binOp = spv::OpShiftLeftLogical;
5517 break;
5518 case glslang::EOpAnd:
5519 case glslang::EOpAndAssign:
5520 binOp = spv::OpBitwiseAnd;
5521 break;
5522 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005523 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005524 binOp = spv::OpLogicalAnd;
5525 break;
5526 case glslang::EOpInclusiveOr:
5527 case glslang::EOpInclusiveOrAssign:
5528 binOp = spv::OpBitwiseOr;
5529 break;
5530 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005531 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005532 binOp = spv::OpLogicalOr;
5533 break;
5534 case glslang::EOpExclusiveOr:
5535 case glslang::EOpExclusiveOrAssign:
5536 binOp = spv::OpBitwiseXor;
5537 break;
5538 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005539 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005540 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005541 break;
5542
Ian Romanickb3bd4022019-01-21 08:57:25 -08005543 case glslang::EOpAbsDifference:
5544 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5545 break;
5546
5547 case glslang::EOpAddSaturate:
5548 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5549 break;
5550
5551 case glslang::EOpSubSaturate:
5552 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5553 break;
5554
5555 case glslang::EOpAverage:
5556 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5557 break;
5558
5559 case glslang::EOpAverageRounded:
5560 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5561 break;
5562
5563 case glslang::EOpMul32x16:
5564 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5565 break;
5566
John Kessenich140f3df2015-06-26 16:58:36 -06005567 case glslang::EOpLessThan:
5568 case glslang::EOpGreaterThan:
5569 case glslang::EOpLessThanEqual:
5570 case glslang::EOpGreaterThanEqual:
5571 case glslang::EOpEqual:
5572 case glslang::EOpNotEqual:
5573 case glslang::EOpVectorEqual:
5574 case glslang::EOpVectorNotEqual:
5575 comparison = true;
5576 break;
5577 default:
5578 break;
5579 }
5580
John Kessenich7c1aa102015-10-15 13:29:11 -06005581 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005582 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005583 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005584 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5585 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005586 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005587
5588 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005589 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005590 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005591
qining25262b32016-05-06 17:25:16 -04005592 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005593 decorations.addNoContraction(builder, result);
5594 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005595 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005596 }
5597
5598 if (! comparison)
5599 return 0;
5600
John Kessenich7c1aa102015-10-15 13:29:11 -06005601 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005602
John Kessenich4583b612016-08-07 19:14:22 -06005603 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005604 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5605 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005606 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005607 return result;
5608 }
John Kessenich140f3df2015-06-26 16:58:36 -06005609
5610 switch (op) {
5611 case glslang::EOpLessThan:
5612 if (isFloat)
5613 binOp = spv::OpFOrdLessThan;
5614 else if (isUnsigned)
5615 binOp = spv::OpULessThan;
5616 else
5617 binOp = spv::OpSLessThan;
5618 break;
5619 case glslang::EOpGreaterThan:
5620 if (isFloat)
5621 binOp = spv::OpFOrdGreaterThan;
5622 else if (isUnsigned)
5623 binOp = spv::OpUGreaterThan;
5624 else
5625 binOp = spv::OpSGreaterThan;
5626 break;
5627 case glslang::EOpLessThanEqual:
5628 if (isFloat)
5629 binOp = spv::OpFOrdLessThanEqual;
5630 else if (isUnsigned)
5631 binOp = spv::OpULessThanEqual;
5632 else
5633 binOp = spv::OpSLessThanEqual;
5634 break;
5635 case glslang::EOpGreaterThanEqual:
5636 if (isFloat)
5637 binOp = spv::OpFOrdGreaterThanEqual;
5638 else if (isUnsigned)
5639 binOp = spv::OpUGreaterThanEqual;
5640 else
5641 binOp = spv::OpSGreaterThanEqual;
5642 break;
5643 case glslang::EOpEqual:
5644 case glslang::EOpVectorEqual:
5645 if (isFloat)
5646 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005647 else if (isBool)
5648 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005649 else
5650 binOp = spv::OpIEqual;
5651 break;
5652 case glslang::EOpNotEqual:
5653 case glslang::EOpVectorNotEqual:
5654 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005655 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005656 else if (isBool)
5657 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005658 else
5659 binOp = spv::OpINotEqual;
5660 break;
5661 default:
5662 break;
5663 }
5664
qining25262b32016-05-06 17:25:16 -04005665 if (binOp != spv::OpNop) {
5666 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005667 decorations.addNoContraction(builder, result);
5668 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005669 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005670 }
John Kessenich140f3df2015-06-26 16:58:36 -06005671
5672 return 0;
5673}
5674
John Kessenich04bb8a02015-12-12 12:28:14 -07005675//
5676// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5677// These can be any of:
5678//
5679// matrix * scalar
5680// scalar * matrix
5681// matrix * matrix linear algebraic
5682// matrix * vector
5683// vector * matrix
5684// matrix * matrix componentwise
5685// matrix op matrix op in {+, -, /}
5686// matrix op scalar op in {+, -, /}
5687// scalar op matrix op in {+, -, /}
5688//
John Kessenichead86222018-03-28 18:01:20 -06005689spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5690 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005691{
5692 bool firstClass = true;
5693
5694 // First, handle first-class matrix operations (* and matrix/scalar)
5695 switch (op) {
5696 case spv::OpFDiv:
5697 if (builder.isMatrix(left) && builder.isScalar(right)) {
5698 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005699 spv::Id resultType = builder.getTypeId(right);
5700 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005701 op = spv::OpMatrixTimesScalar;
5702 } else
5703 firstClass = false;
5704 break;
5705 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005706 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005707 std::swap(left, right);
5708 assert(builder.isScalar(right));
5709 break;
5710 case spv::OpVectorTimesMatrix:
5711 assert(builder.isVector(left));
5712 assert(builder.isMatrix(right));
5713 break;
5714 case spv::OpMatrixTimesVector:
5715 assert(builder.isMatrix(left));
5716 assert(builder.isVector(right));
5717 break;
5718 case spv::OpMatrixTimesMatrix:
5719 assert(builder.isMatrix(left));
5720 assert(builder.isMatrix(right));
5721 break;
5722 default:
5723 firstClass = false;
5724 break;
5725 }
5726
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005727 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5728 firstClass = true;
5729
qining25262b32016-05-06 17:25:16 -04005730 if (firstClass) {
5731 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005732 decorations.addNoContraction(builder, result);
5733 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005734 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005735 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005736
LoopDawg592860c2016-06-09 08:57:35 -06005737 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005738 // The result type of all of them is the same type as the (a) matrix operand.
5739 // The algorithm is to:
5740 // - break the matrix(es) into vectors
5741 // - smear any scalar to a vector
5742 // - do vector operations
5743 // - make a matrix out the vector results
5744 switch (op) {
5745 case spv::OpFAdd:
5746 case spv::OpFSub:
5747 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005748 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005749 case spv::OpFMul:
5750 {
5751 // one time set up...
5752 bool leftMat = builder.isMatrix(left);
5753 bool rightMat = builder.isMatrix(right);
5754 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5755 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5756 spv::Id scalarType = builder.getScalarTypeId(typeId);
5757 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5758 std::vector<spv::Id> results;
5759 spv::Id smearVec = spv::NoResult;
5760 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005761 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005762 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005763 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005764
5765 // do each vector op
5766 for (unsigned int c = 0; c < numCols; ++c) {
5767 std::vector<unsigned int> indexes;
5768 indexes.push_back(c);
5769 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5770 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005771 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005772 decorations.addNoContraction(builder, result);
5773 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005774 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005775 }
5776
5777 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005778 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005779 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005780 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005781 }
5782 default:
5783 assert(0);
5784 return spv::NoResult;
5785 }
5786}
5787
John Kessenichead86222018-03-28 18:01:20 -06005788spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005789 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005790{
5791 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005792 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005793 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005794 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5795 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005796
5797 switch (op) {
5798 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005799 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005800 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005801 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005802 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005803 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005804 unaryOp = spv::OpSNegate;
5805 break;
5806
5807 case glslang::EOpLogicalNot:
5808 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005809 unaryOp = spv::OpLogicalNot;
5810 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005811 case glslang::EOpBitwiseNot:
5812 unaryOp = spv::OpNot;
5813 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005814
John Kessenich140f3df2015-06-26 16:58:36 -06005815 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005816 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005817 break;
5818 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005819 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005820 break;
5821 case glslang::EOpTranspose:
5822 unaryOp = spv::OpTranspose;
5823 break;
5824
5825 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005826 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005827 break;
5828 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005829 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005830 break;
5831 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005832 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005833 break;
5834 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005835 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005836 break;
5837 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005838 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005839 break;
5840 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005841 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005842 break;
5843 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005844 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005847 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
5849
5850 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005851 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005852 break;
5853 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005854 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005855 break;
5856 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005857 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005858 break;
5859 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005860 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005861 break;
5862 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005863 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005864 break;
5865 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005866 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005867 break;
5868
5869 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005870 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005871 break;
5872 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005873 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005874 break;
5875
5876 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005877 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005878 break;
5879 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005880 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005881 break;
5882 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005883 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005884 break;
5885 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005886 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005887 break;
5888 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005889 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005890 break;
5891 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005892 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005893 break;
5894
5895 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005896 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005897 break;
5898 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005899 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005900 break;
5901 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005902 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005903 break;
5904 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005905 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005906 break;
5907 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005908 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005909 break;
5910 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005911 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005912 break;
5913
5914 case glslang::EOpIsNan:
5915 unaryOp = spv::OpIsNan;
5916 break;
5917 case glslang::EOpIsInf:
5918 unaryOp = spv::OpIsInf;
5919 break;
LoopDawg592860c2016-06-09 08:57:35 -06005920 case glslang::EOpIsFinite:
5921 unaryOp = spv::OpIsFinite;
5922 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005923
Rex Xucbc426e2015-12-15 16:03:10 +08005924 case glslang::EOpFloatBitsToInt:
5925 case glslang::EOpFloatBitsToUint:
5926 case glslang::EOpIntBitsToFloat:
5927 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005928 case glslang::EOpDoubleBitsToInt64:
5929 case glslang::EOpDoubleBitsToUint64:
5930 case glslang::EOpInt64BitsToDouble:
5931 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005932 case glslang::EOpFloat16BitsToInt16:
5933 case glslang::EOpFloat16BitsToUint16:
5934 case glslang::EOpInt16BitsToFloat16:
5935 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005936 unaryOp = spv::OpBitcast;
5937 break;
5938
John Kessenich140f3df2015-06-26 16:58:36 -06005939 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005940 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005941 break;
5942 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005943 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005944 break;
5945 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005946 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005947 break;
5948 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005949 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005950 break;
5951 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005952 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005953 break;
5954 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005955 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005956 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005957#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005958 case glslang::EOpPackSnorm4x8:
5959 libCall = spv::GLSLstd450PackSnorm4x8;
5960 break;
5961 case glslang::EOpUnpackSnorm4x8:
5962 libCall = spv::GLSLstd450UnpackSnorm4x8;
5963 break;
5964 case glslang::EOpPackUnorm4x8:
5965 libCall = spv::GLSLstd450PackUnorm4x8;
5966 break;
5967 case glslang::EOpUnpackUnorm4x8:
5968 libCall = spv::GLSLstd450UnpackUnorm4x8;
5969 break;
5970 case glslang::EOpPackDouble2x32:
5971 libCall = spv::GLSLstd450PackDouble2x32;
5972 break;
5973 case glslang::EOpUnpackDouble2x32:
5974 libCall = spv::GLSLstd450UnpackDouble2x32;
5975 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005976#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005977
Rex Xu8ff43de2016-04-22 16:51:45 +08005978 case glslang::EOpPackInt2x32:
5979 case glslang::EOpUnpackInt2x32:
5980 case glslang::EOpPackUint2x32:
5981 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005982 case glslang::EOpPack16:
5983 case glslang::EOpPack32:
5984 case glslang::EOpPack64:
5985 case glslang::EOpUnpack32:
5986 case glslang::EOpUnpack16:
5987 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005988 case glslang::EOpPackInt2x16:
5989 case glslang::EOpUnpackInt2x16:
5990 case glslang::EOpPackUint2x16:
5991 case glslang::EOpUnpackUint2x16:
5992 case glslang::EOpPackInt4x16:
5993 case glslang::EOpUnpackInt4x16:
5994 case glslang::EOpPackUint4x16:
5995 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005996 case glslang::EOpPackFloat2x16:
5997 case glslang::EOpUnpackFloat2x16:
5998 unaryOp = spv::OpBitcast;
5999 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006000
John Kessenich140f3df2015-06-26 16:58:36 -06006001 case glslang::EOpDPdx:
6002 unaryOp = spv::OpDPdx;
6003 break;
6004 case glslang::EOpDPdy:
6005 unaryOp = spv::OpDPdy;
6006 break;
6007 case glslang::EOpFwidth:
6008 unaryOp = spv::OpFwidth;
6009 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006010
John Kessenich140f3df2015-06-26 16:58:36 -06006011 case glslang::EOpAny:
6012 unaryOp = spv::OpAny;
6013 break;
6014 case glslang::EOpAll:
6015 unaryOp = spv::OpAll;
6016 break;
6017
6018 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006019 if (isFloat)
6020 libCall = spv::GLSLstd450FAbs;
6021 else
6022 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006023 break;
6024 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006025 if (isFloat)
6026 libCall = spv::GLSLstd450FSign;
6027 else
6028 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006029 break;
6030
John Kessenicha28f7a72019-08-06 07:00:58 -06006031#ifndef GLSLANG_WEB
6032 case glslang::EOpDPdxFine:
6033 unaryOp = spv::OpDPdxFine;
6034 break;
6035 case glslang::EOpDPdyFine:
6036 unaryOp = spv::OpDPdyFine;
6037 break;
6038 case glslang::EOpFwidthFine:
6039 unaryOp = spv::OpFwidthFine;
6040 break;
6041 case glslang::EOpDPdxCoarse:
6042 unaryOp = spv::OpDPdxCoarse;
6043 break;
6044 case glslang::EOpDPdyCoarse:
6045 unaryOp = spv::OpDPdyCoarse;
6046 break;
6047 case glslang::EOpFwidthCoarse:
6048 unaryOp = spv::OpFwidthCoarse;
6049 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006050 case glslang::EOpRayQueryProceed:
6051 unaryOp = spv::OpRayQueryProceedKHR;
6052 break;
6053 case glslang::EOpRayQueryGetRayTMin:
6054 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6055 break;
6056 case glslang::EOpRayQueryGetRayFlags:
6057 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6058 break;
6059 case glslang::EOpRayQueryGetWorldRayOrigin:
6060 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6061 break;
6062 case glslang::EOpRayQueryGetWorldRayDirection:
6063 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6064 break;
6065 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6066 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6067 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006068 case glslang::EOpInterpolateAtCentroid:
6069 if (typeProxy == glslang::EbtFloat16)
6070 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6071 libCall = spv::GLSLstd450InterpolateAtCentroid;
6072 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006073 case glslang::EOpAtomicCounterIncrement:
6074 case glslang::EOpAtomicCounterDecrement:
6075 case glslang::EOpAtomicCounter:
6076 {
6077 // Handle all of the atomics in one place, in createAtomicOperation()
6078 std::vector<spv::Id> operands;
6079 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006080 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006081 }
6082
John Kessenichfc51d282015-08-19 13:34:18 -06006083 case glslang::EOpBitFieldReverse:
6084 unaryOp = spv::OpBitReverse;
6085 break;
6086 case glslang::EOpBitCount:
6087 unaryOp = spv::OpBitCount;
6088 break;
6089 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006090 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006091 break;
6092 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006093 if (isUnsigned)
6094 libCall = spv::GLSLstd450FindUMsb;
6095 else
6096 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006097 break;
6098
Ian Romanickb3bd4022019-01-21 08:57:25 -08006099 case glslang::EOpCountLeadingZeros:
6100 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6101 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6102 unaryOp = spv::OpUCountLeadingZerosINTEL;
6103 break;
6104
6105 case glslang::EOpCountTrailingZeros:
6106 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6107 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6108 unaryOp = spv::OpUCountTrailingZerosINTEL;
6109 break;
6110
Rex Xu574ab042016-04-14 16:53:07 +08006111 case glslang::EOpBallot:
6112 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006113 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006114 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006115 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006116 case glslang::EOpMinInvocations:
6117 case glslang::EOpMaxInvocations:
6118 case glslang::EOpAddInvocations:
6119 case glslang::EOpMinInvocationsNonUniform:
6120 case glslang::EOpMaxInvocationsNonUniform:
6121 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006122 case glslang::EOpMinInvocationsInclusiveScan:
6123 case glslang::EOpMaxInvocationsInclusiveScan:
6124 case glslang::EOpAddInvocationsInclusiveScan:
6125 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6126 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6127 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6128 case glslang::EOpMinInvocationsExclusiveScan:
6129 case glslang::EOpMaxInvocationsExclusiveScan:
6130 case glslang::EOpAddInvocationsExclusiveScan:
6131 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6132 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6133 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006134 {
6135 std::vector<spv::Id> operands;
6136 operands.push_back(operand);
6137 return createInvocationsOperation(op, typeId, operands, typeProxy);
6138 }
John Kessenich66011cb2018-03-06 16:12:04 -07006139 case glslang::EOpSubgroupAll:
6140 case glslang::EOpSubgroupAny:
6141 case glslang::EOpSubgroupAllEqual:
6142 case glslang::EOpSubgroupBroadcastFirst:
6143 case glslang::EOpSubgroupBallot:
6144 case glslang::EOpSubgroupInverseBallot:
6145 case glslang::EOpSubgroupBallotBitCount:
6146 case glslang::EOpSubgroupBallotInclusiveBitCount:
6147 case glslang::EOpSubgroupBallotExclusiveBitCount:
6148 case glslang::EOpSubgroupBallotFindLSB:
6149 case glslang::EOpSubgroupBallotFindMSB:
6150 case glslang::EOpSubgroupAdd:
6151 case glslang::EOpSubgroupMul:
6152 case glslang::EOpSubgroupMin:
6153 case glslang::EOpSubgroupMax:
6154 case glslang::EOpSubgroupAnd:
6155 case glslang::EOpSubgroupOr:
6156 case glslang::EOpSubgroupXor:
6157 case glslang::EOpSubgroupInclusiveAdd:
6158 case glslang::EOpSubgroupInclusiveMul:
6159 case glslang::EOpSubgroupInclusiveMin:
6160 case glslang::EOpSubgroupInclusiveMax:
6161 case glslang::EOpSubgroupInclusiveAnd:
6162 case glslang::EOpSubgroupInclusiveOr:
6163 case glslang::EOpSubgroupInclusiveXor:
6164 case glslang::EOpSubgroupExclusiveAdd:
6165 case glslang::EOpSubgroupExclusiveMul:
6166 case glslang::EOpSubgroupExclusiveMin:
6167 case glslang::EOpSubgroupExclusiveMax:
6168 case glslang::EOpSubgroupExclusiveAnd:
6169 case glslang::EOpSubgroupExclusiveOr:
6170 case glslang::EOpSubgroupExclusiveXor:
6171 case glslang::EOpSubgroupQuadSwapHorizontal:
6172 case glslang::EOpSubgroupQuadSwapVertical:
6173 case glslang::EOpSubgroupQuadSwapDiagonal: {
6174 std::vector<spv::Id> operands;
6175 operands.push_back(operand);
6176 return createSubgroupOperation(op, typeId, operands, typeProxy);
6177 }
Rex Xu9d93a232016-05-05 12:30:44 +08006178 case glslang::EOpMbcnt:
6179 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6180 libCall = spv::MbcntAMD;
6181 break;
6182
6183 case glslang::EOpCubeFaceIndex:
6184 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6185 libCall = spv::CubeFaceIndexAMD;
6186 break;
6187
6188 case glslang::EOpCubeFaceCoord:
6189 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6190 libCall = spv::CubeFaceCoordAMD;
6191 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006192 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006193 unaryOp = spv::OpGroupNonUniformPartitionNV;
6194 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006195 case glslang::EOpConstructReference:
6196 unaryOp = spv::OpBitcast;
6197 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006198#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006199
6200 case glslang::EOpCopyObject:
6201 unaryOp = spv::OpCopyObject;
6202 break;
6203
John Kessenich140f3df2015-06-26 16:58:36 -06006204 default:
6205 return 0;
6206 }
6207
6208 spv::Id id;
6209 if (libCall >= 0) {
6210 std::vector<spv::Id> args;
6211 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006212 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006213 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006214 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006215 }
John Kessenich140f3df2015-06-26 16:58:36 -06006216
John Kessenichb9197c82019-08-11 07:41:45 -06006217 decorations.addNoContraction(builder, id);
6218 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006219 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006220}
6221
John Kessenich7a53f762016-01-20 11:19:27 -07006222// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006223spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6224 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006225{
6226 // Handle unary operations vector by vector.
6227 // The result type is the same type as the original type.
6228 // The algorithm is to:
6229 // - break the matrix into vectors
6230 // - apply the operation to each vector
6231 // - make a matrix out the vector results
6232
6233 // get the types sorted out
6234 int numCols = builder.getNumColumns(operand);
6235 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006236 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6237 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006238 std::vector<spv::Id> results;
6239
6240 // do each vector op
6241 for (int c = 0; c < numCols; ++c) {
6242 std::vector<unsigned int> indexes;
6243 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006244 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6245 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006246 decorations.addNoContraction(builder, destVec);
6247 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006248 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006249 }
6250
6251 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006252 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006253 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006254 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006255}
6256
John Kessenichad7645f2018-06-04 19:11:25 -06006257// For converting integers where both the bitwidth and the signedness could
6258// change, but only do the width change here. The caller is still responsible
6259// for the signedness conversion.
6260spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006261{
John Kessenichad7645f2018-06-04 19:11:25 -06006262 // Get the result type width, based on the type to convert to.
6263 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006264 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006265 case glslang::EOpConvInt16ToUint8:
6266 case glslang::EOpConvIntToUint8:
6267 case glslang::EOpConvInt64ToUint8:
6268 case glslang::EOpConvUint16ToInt8:
6269 case glslang::EOpConvUintToInt8:
6270 case glslang::EOpConvUint64ToInt8:
6271 width = 8;
6272 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006273 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006274 case glslang::EOpConvIntToUint16:
6275 case glslang::EOpConvInt64ToUint16:
6276 case glslang::EOpConvUint8ToInt16:
6277 case glslang::EOpConvUintToInt16:
6278 case glslang::EOpConvUint64ToInt16:
6279 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006280 break;
6281 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006282 case glslang::EOpConvInt16ToUint:
6283 case glslang::EOpConvInt64ToUint:
6284 case glslang::EOpConvUint8ToInt:
6285 case glslang::EOpConvUint16ToInt:
6286 case glslang::EOpConvUint64ToInt:
6287 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006288 break;
6289 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006290 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006291 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006292 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006293 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006294 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006295 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006296 break;
6297
6298 default:
6299 assert(false && "Default missing");
6300 break;
6301 }
6302
John Kessenichad7645f2018-06-04 19:11:25 -06006303 // Get the conversion operation and result type,
6304 // based on the target width, but the source type.
6305 spv::Id type = spv::NoType;
6306 spv::Op convOp = spv::OpNop;
6307 switch(op) {
6308 case glslang::EOpConvInt8ToUint16:
6309 case glslang::EOpConvInt8ToUint:
6310 case glslang::EOpConvInt8ToUint64:
6311 case glslang::EOpConvInt16ToUint8:
6312 case glslang::EOpConvInt16ToUint:
6313 case glslang::EOpConvInt16ToUint64:
6314 case glslang::EOpConvIntToUint8:
6315 case glslang::EOpConvIntToUint16:
6316 case glslang::EOpConvIntToUint64:
6317 case glslang::EOpConvInt64ToUint8:
6318 case glslang::EOpConvInt64ToUint16:
6319 case glslang::EOpConvInt64ToUint:
6320 convOp = spv::OpSConvert;
6321 type = builder.makeIntType(width);
6322 break;
6323 default:
6324 convOp = spv::OpUConvert;
6325 type = builder.makeUintType(width);
6326 break;
6327 }
6328
John Kessenich66011cb2018-03-06 16:12:04 -07006329 if (vectorSize > 0)
6330 type = builder.makeVectorType(type, vectorSize);
6331
John Kessenichad7645f2018-06-04 19:11:25 -06006332 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006333}
6334
John Kessenichead86222018-03-28 18:01:20 -06006335spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6336 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006337{
6338 spv::Op convOp = spv::OpNop;
6339 spv::Id zero = 0;
6340 spv::Id one = 0;
6341
6342 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6343
6344 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006345 case glslang::EOpConvIntToBool:
6346 case glslang::EOpConvUintToBool:
6347 zero = builder.makeUintConstant(0);
6348 zero = makeSmearedConstant(zero, vectorSize);
6349 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006350 case glslang::EOpConvFloatToBool:
6351 zero = builder.makeFloatConstant(0.0F);
6352 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006353 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006354 case glslang::EOpConvBoolToFloat:
6355 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006356 zero = builder.makeFloatConstant(0.0F);
6357 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006358 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006359
John Kessenich140f3df2015-06-26 16:58:36 -06006360 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006361 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006362#ifndef GLSLANG_WEB
6363 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006364 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006365 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006366 } else
6367#endif
6368 {
6369 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006370 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006371 }
Rex Xucabbb782017-03-24 13:41:14 +08006372
John Kessenich140f3df2015-06-26 16:58:36 -06006373 convOp = spv::OpSelect;
6374 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006375
John Kessenich140f3df2015-06-26 16:58:36 -06006376 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006377 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006378#ifndef GLSLANG_WEB
6379 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006380 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006381 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006382 } else
6383#endif
6384 {
6385 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006386 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006387 }
Rex Xucabbb782017-03-24 13:41:14 +08006388
John Kessenich140f3df2015-06-26 16:58:36 -06006389 convOp = spv::OpSelect;
6390 break;
6391
John Kessenich66011cb2018-03-06 16:12:04 -07006392 case glslang::EOpConvInt8ToFloat16:
6393 case glslang::EOpConvInt8ToFloat:
6394 case glslang::EOpConvInt8ToDouble:
6395 case glslang::EOpConvInt16ToFloat16:
6396 case glslang::EOpConvInt16ToFloat:
6397 case glslang::EOpConvInt16ToDouble:
6398 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006399 case glslang::EOpConvIntToFloat:
6400 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006401 case glslang::EOpConvInt64ToFloat:
6402 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006403 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006404 convOp = spv::OpConvertSToF;
6405 break;
6406
John Kessenich66011cb2018-03-06 16:12:04 -07006407 case glslang::EOpConvUint8ToFloat16:
6408 case glslang::EOpConvUint8ToFloat:
6409 case glslang::EOpConvUint8ToDouble:
6410 case glslang::EOpConvUint16ToFloat16:
6411 case glslang::EOpConvUint16ToFloat:
6412 case glslang::EOpConvUint16ToDouble:
6413 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006414 case glslang::EOpConvUintToFloat:
6415 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006416 case glslang::EOpConvUint64ToFloat:
6417 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006418 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006419 convOp = spv::OpConvertUToF;
6420 break;
6421
John Kessenich66011cb2018-03-06 16:12:04 -07006422 case glslang::EOpConvFloat16ToInt8:
6423 case glslang::EOpConvFloatToInt8:
6424 case glslang::EOpConvDoubleToInt8:
6425 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006426 case glslang::EOpConvFloatToInt16:
6427 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006428 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006429 case glslang::EOpConvFloatToInt:
6430 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006431 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006432 case glslang::EOpConvFloatToInt64:
6433 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006434 convOp = spv::OpConvertFToS;
6435 break;
6436
John Kessenich66011cb2018-03-06 16:12:04 -07006437 case glslang::EOpConvUint8ToInt8:
6438 case glslang::EOpConvInt8ToUint8:
6439 case glslang::EOpConvUint16ToInt16:
6440 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006441 case glslang::EOpConvUintToInt:
6442 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006443 case glslang::EOpConvUint64ToInt64:
6444 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006445 if (builder.isInSpecConstCodeGenMode()) {
6446 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006447#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006448 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6449 zero = builder.makeUint8Constant(0);
6450 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006451 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006452 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6453 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006454 } else
6455#endif
6456 {
Rex Xucabbb782017-03-24 13:41:14 +08006457 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006458 }
qining189b2032016-04-12 23:16:20 -04006459 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006460 // Use OpIAdd, instead of OpBitcast to do the conversion when
6461 // generating for OpSpecConstantOp instruction.
6462 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6463 }
6464 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006465 convOp = spv::OpBitcast;
6466 break;
6467
John Kessenich66011cb2018-03-06 16:12:04 -07006468 case glslang::EOpConvFloat16ToUint8:
6469 case glslang::EOpConvFloatToUint8:
6470 case glslang::EOpConvDoubleToUint8:
6471 case glslang::EOpConvFloat16ToUint16:
6472 case glslang::EOpConvFloatToUint16:
6473 case glslang::EOpConvDoubleToUint16:
6474 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006475 case glslang::EOpConvFloatToUint:
6476 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006477 case glslang::EOpConvFloatToUint64:
6478 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006479 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006480 convOp = spv::OpConvertFToU;
6481 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006482
John Kessenich39697cd2019-08-08 10:35:51 -06006483#ifndef GLSLANG_WEB
6484 case glslang::EOpConvInt8ToBool:
6485 case glslang::EOpConvUint8ToBool:
6486 zero = builder.makeUint8Constant(0);
6487 zero = makeSmearedConstant(zero, vectorSize);
6488 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6489 case glslang::EOpConvInt16ToBool:
6490 case glslang::EOpConvUint16ToBool:
6491 zero = builder.makeUint16Constant(0);
6492 zero = makeSmearedConstant(zero, vectorSize);
6493 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6494 case glslang::EOpConvInt64ToBool:
6495 case glslang::EOpConvUint64ToBool:
6496 zero = builder.makeUint64Constant(0);
6497 zero = makeSmearedConstant(zero, vectorSize);
6498 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6499 case glslang::EOpConvDoubleToBool:
6500 zero = builder.makeDoubleConstant(0.0);
6501 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006502 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006503 case glslang::EOpConvFloat16ToBool:
6504 zero = builder.makeFloat16Constant(0.0F);
6505 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006506 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006507 case glslang::EOpConvBoolToDouble:
6508 convOp = spv::OpSelect;
6509 zero = builder.makeDoubleConstant(0.0);
6510 one = builder.makeDoubleConstant(1.0);
6511 break;
6512 case glslang::EOpConvBoolToFloat16:
6513 convOp = spv::OpSelect;
6514 zero = builder.makeFloat16Constant(0.0F);
6515 one = builder.makeFloat16Constant(1.0F);
6516 break;
6517 case glslang::EOpConvBoolToInt8:
6518 zero = builder.makeInt8Constant(0);
6519 one = builder.makeInt8Constant(1);
6520 convOp = spv::OpSelect;
6521 break;
6522 case glslang::EOpConvBoolToUint8:
6523 zero = builder.makeUint8Constant(0);
6524 one = builder.makeUint8Constant(1);
6525 convOp = spv::OpSelect;
6526 break;
6527 case glslang::EOpConvBoolToInt16:
6528 zero = builder.makeInt16Constant(0);
6529 one = builder.makeInt16Constant(1);
6530 convOp = spv::OpSelect;
6531 break;
6532 case glslang::EOpConvBoolToUint16:
6533 zero = builder.makeUint16Constant(0);
6534 one = builder.makeUint16Constant(1);
6535 convOp = spv::OpSelect;
6536 break;
6537 case glslang::EOpConvDoubleToFloat:
6538 case glslang::EOpConvFloatToDouble:
6539 case glslang::EOpConvDoubleToFloat16:
6540 case glslang::EOpConvFloat16ToDouble:
6541 case glslang::EOpConvFloatToFloat16:
6542 case glslang::EOpConvFloat16ToFloat:
6543 convOp = spv::OpFConvert;
6544 if (builder.isMatrixType(destType))
6545 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6546 break;
6547
John Kessenich66011cb2018-03-06 16:12:04 -07006548 case glslang::EOpConvInt8ToInt16:
6549 case glslang::EOpConvInt8ToInt:
6550 case glslang::EOpConvInt8ToInt64:
6551 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006552 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006553 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006554 case glslang::EOpConvIntToInt8:
6555 case glslang::EOpConvIntToInt16:
6556 case glslang::EOpConvIntToInt64:
6557 case glslang::EOpConvInt64ToInt8:
6558 case glslang::EOpConvInt64ToInt16:
6559 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006560 convOp = spv::OpSConvert;
6561 break;
6562
John Kessenich66011cb2018-03-06 16:12:04 -07006563 case glslang::EOpConvUint8ToUint16:
6564 case glslang::EOpConvUint8ToUint:
6565 case glslang::EOpConvUint8ToUint64:
6566 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006567 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006568 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006569 case glslang::EOpConvUintToUint8:
6570 case glslang::EOpConvUintToUint16:
6571 case glslang::EOpConvUintToUint64:
6572 case glslang::EOpConvUint64ToUint8:
6573 case glslang::EOpConvUint64ToUint16:
6574 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006575 convOp = spv::OpUConvert;
6576 break;
6577
John Kessenich66011cb2018-03-06 16:12:04 -07006578 case glslang::EOpConvInt8ToUint16:
6579 case glslang::EOpConvInt8ToUint:
6580 case glslang::EOpConvInt8ToUint64:
6581 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006582 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006583 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006584 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006585 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006586 case glslang::EOpConvIntToUint64:
6587 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006588 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006589 case glslang::EOpConvInt64ToUint:
6590 case glslang::EOpConvUint8ToInt16:
6591 case glslang::EOpConvUint8ToInt:
6592 case glslang::EOpConvUint8ToInt64:
6593 case glslang::EOpConvUint16ToInt8:
6594 case glslang::EOpConvUint16ToInt:
6595 case glslang::EOpConvUint16ToInt64:
6596 case glslang::EOpConvUintToInt8:
6597 case glslang::EOpConvUintToInt16:
6598 case glslang::EOpConvUintToInt64:
6599 case glslang::EOpConvUint64ToInt8:
6600 case glslang::EOpConvUint64ToInt16:
6601 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006602 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006603 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006604
6605 if (builder.isInSpecConstCodeGenMode()) {
6606 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006607 switch(op) {
6608 case glslang::EOpConvInt16ToUint8:
6609 case glslang::EOpConvIntToUint8:
6610 case glslang::EOpConvInt64ToUint8:
6611 case glslang::EOpConvUint16ToInt8:
6612 case glslang::EOpConvUintToInt8:
6613 case glslang::EOpConvUint64ToInt8:
6614 zero = builder.makeUint8Constant(0);
6615 break;
6616 case glslang::EOpConvInt8ToUint16:
6617 case glslang::EOpConvIntToUint16:
6618 case glslang::EOpConvInt64ToUint16:
6619 case glslang::EOpConvUint8ToInt16:
6620 case glslang::EOpConvUintToInt16:
6621 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006622 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006623 break;
6624 case glslang::EOpConvInt8ToUint:
6625 case glslang::EOpConvInt16ToUint:
6626 case glslang::EOpConvInt64ToUint:
6627 case glslang::EOpConvUint8ToInt:
6628 case glslang::EOpConvUint16ToInt:
6629 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006630 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006631 break;
6632 case glslang::EOpConvInt8ToUint64:
6633 case glslang::EOpConvInt16ToUint64:
6634 case glslang::EOpConvIntToUint64:
6635 case glslang::EOpConvUint8ToInt64:
6636 case glslang::EOpConvUint16ToInt64:
6637 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006638 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006639 break;
6640 default:
6641 assert(false && "Default missing");
6642 break;
6643 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006644 zero = makeSmearedConstant(zero, vectorSize);
6645 // Use OpIAdd, instead of OpBitcast to do the conversion when
6646 // generating for OpSpecConstantOp instruction.
6647 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6648 }
6649 // For normal run-time conversion instruction, use OpBitcast.
6650 convOp = spv::OpBitcast;
6651 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006652 case glslang::EOpConvUint64ToPtr:
6653 convOp = spv::OpConvertUToPtr;
6654 break;
6655 case glslang::EOpConvPtrToUint64:
6656 convOp = spv::OpConvertPtrToU;
6657 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006658 case glslang::EOpConvPtrToUvec2:
6659 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006660 if (builder.isVector(operand))
6661 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6662 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006663 convOp = spv::OpBitcast;
6664 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006665#endif
6666
John Kessenich140f3df2015-06-26 16:58:36 -06006667 default:
6668 break;
6669 }
6670
6671 spv::Id result = 0;
6672 if (convOp == spv::OpNop)
6673 return result;
6674
6675 if (convOp == spv::OpSelect) {
6676 zero = makeSmearedConstant(zero, vectorSize);
6677 one = makeSmearedConstant(one, vectorSize);
6678 result = builder.createTriOp(convOp, destType, operand, one, zero);
6679 } else
6680 result = builder.createUnaryOp(convOp, destType, operand);
6681
John Kessenichead86222018-03-28 18:01:20 -06006682 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006683 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006684 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006685}
6686
6687spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6688{
6689 if (vectorSize == 0)
6690 return constant;
6691
6692 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6693 std::vector<spv::Id> components;
6694 for (int c = 0; c < vectorSize; ++c)
6695 components.push_back(constant);
6696 return builder.makeCompositeConstant(vectorTypeId, components);
6697}
6698
John Kessenich426394d2015-07-23 10:22:48 -06006699// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006700spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6701 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6702 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006703{
6704 spv::Op opCode = spv::OpNop;
6705
6706 switch (op) {
6707 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006708 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006709 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006710 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006711 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6712 opCode = spv::OpAtomicFAddEXT;
6713 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6714 if (typeProxy == glslang::EbtFloat)
6715 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6716 else
6717 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6718 }
John Kessenich426394d2015-07-23 10:22:48 -06006719 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006720 case glslang::EOpAtomicCounterSubtract:
6721 opCode = spv::OpAtomicISub;
6722 break;
John Kessenich426394d2015-07-23 10:22:48 -06006723 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006724 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006725 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006726 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6727 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006728 break;
6729 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006730 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006731 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006732 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6733 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006734 break;
6735 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006736 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006737 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006738 opCode = spv::OpAtomicAnd;
6739 break;
6740 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006741 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006742 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006743 opCode = spv::OpAtomicOr;
6744 break;
6745 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006746 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006747 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006748 opCode = spv::OpAtomicXor;
6749 break;
6750 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006751 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006752 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006753 opCode = spv::OpAtomicExchange;
6754 break;
6755 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006756 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006757 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006758 opCode = spv::OpAtomicCompareExchange;
6759 break;
6760 case glslang::EOpAtomicCounterIncrement:
6761 opCode = spv::OpAtomicIIncrement;
6762 break;
6763 case glslang::EOpAtomicCounterDecrement:
6764 opCode = spv::OpAtomicIDecrement;
6765 break;
6766 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006767 case glslang::EOpImageAtomicLoad:
6768 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006769 opCode = spv::OpAtomicLoad;
6770 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006771 case glslang::EOpAtomicStore:
6772 case glslang::EOpImageAtomicStore:
6773 opCode = spv::OpAtomicStore;
6774 break;
John Kessenich426394d2015-07-23 10:22:48 -06006775 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006776 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006777 break;
6778 }
6779
Rex Xue8fe8b02017-09-26 15:42:56 +08006780 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6781 builder.addCapability(spv::CapabilityInt64Atomics);
6782
John Kessenich426394d2015-07-23 10:22:48 -06006783 // Sort out the operands
6784 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006785 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006786 // - compare-exchange swaps the value and comparator
6787 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006788 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006789 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6790 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6791 spv::Id scopeId;
6792 if (glslangIntermediate->usingVulkanMemoryModel()) {
6793 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6794 } else {
6795 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6796 }
6797 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006798 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6799 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006800 spv::MemorySemanticsVolatileMask :
6801 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006802 spv::Id semanticsId2 = semanticsId;
6803
6804 pointerId = operands[0];
6805 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6806 // no additional operands
6807 } else if (opCode == spv::OpAtomicCompareExchange) {
6808 compareId = operands[1];
6809 valueId = operands[2];
6810 if (operands.size() > 3) {
6811 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006812 semanticsId = builder.makeUintConstant(
6813 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6814 semanticsId2 = builder.makeUintConstant(
6815 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006816 }
6817 } else if (opCode == spv::OpAtomicLoad) {
6818 if (operands.size() > 1) {
6819 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006820 semanticsId = builder.makeUintConstant(
6821 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006822 }
6823 } else {
6824 // atomic store or RMW
6825 valueId = operands[1];
6826 if (operands.size() > 2) {
6827 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006828 semanticsId = builder.makeUintConstant
6829 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006830 }
Rex Xu04db3f52015-09-16 11:44:02 +08006831 }
John Kessenich426394d2015-07-23 10:22:48 -06006832
Jeff Bolz36831c92018-09-05 10:11:41 -05006833 // Check for capabilities
6834 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006835 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6836 spv::MemorySemanticsMakeVisibleKHRMask |
6837 spv::MemorySemanticsOutputMemoryKHRMask |
6838 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006839 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6840 }
John Kessenich426394d2015-07-23 10:22:48 -06006841
Jeff Bolz36831c92018-09-05 10:11:41 -05006842 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6843 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6844 }
John Kessenich48d6e792017-10-06 21:21:48 -06006845
Jeff Bolz36831c92018-09-05 10:11:41 -05006846 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6847 spvAtomicOperands.push_back(pointerId);
6848 spvAtomicOperands.push_back(scopeId);
6849 spvAtomicOperands.push_back(semanticsId);
6850 if (opCode == spv::OpAtomicCompareExchange) {
6851 spvAtomicOperands.push_back(semanticsId2);
6852 spvAtomicOperands.push_back(valueId);
6853 spvAtomicOperands.push_back(compareId);
6854 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6855 spvAtomicOperands.push_back(valueId);
6856 }
John Kessenich48d6e792017-10-06 21:21:48 -06006857
Jeff Bolz36831c92018-09-05 10:11:41 -05006858 if (opCode == spv::OpAtomicStore) {
6859 builder.createNoResultOp(opCode, spvAtomicOperands);
6860 return 0;
6861 } else {
6862 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6863
6864 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6865 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6866 if (op == glslang::EOpAtomicCounterDecrement)
6867 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6868
6869 return resultId;
6870 }
John Kessenich426394d2015-07-23 10:22:48 -06006871}
6872
John Kessenich91cef522016-05-05 16:45:40 -06006873// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006874spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6875 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006876{
John Kessenich66011cb2018-03-06 16:12:04 -07006877 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6878 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006879
Rex Xu51596642016-09-21 18:56:12 +08006880 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006881 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006882 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6883
chaocf200da82016-12-20 12:44:35 -08006884 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6885 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006886 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6887 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006888 } else if (op == glslang::EOpAnyInvocation ||
6889 op == glslang::EOpAllInvocations ||
6890 op == glslang::EOpAllInvocationsEqual) {
6891 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6892 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006893 } else {
6894 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006895 if (op == glslang::EOpMinInvocationsNonUniform ||
6896 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006897 op == glslang::EOpAddInvocationsNonUniform ||
6898 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6899 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6900 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6901 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6902 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6903 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006904 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006905
Rex Xu430ef402016-10-14 17:22:23 +08006906 switch (op) {
6907 case glslang::EOpMinInvocations:
6908 case glslang::EOpMaxInvocations:
6909 case glslang::EOpAddInvocations:
6910 case glslang::EOpMinInvocationsNonUniform:
6911 case glslang::EOpMaxInvocationsNonUniform:
6912 case glslang::EOpAddInvocationsNonUniform:
6913 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006914 break;
6915 case glslang::EOpMinInvocationsInclusiveScan:
6916 case glslang::EOpMaxInvocationsInclusiveScan:
6917 case glslang::EOpAddInvocationsInclusiveScan:
6918 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6919 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6920 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6921 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006922 break;
6923 case glslang::EOpMinInvocationsExclusiveScan:
6924 case glslang::EOpMaxInvocationsExclusiveScan:
6925 case glslang::EOpAddInvocationsExclusiveScan:
6926 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6927 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6928 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6929 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006930 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006931 default:
6932 break;
Rex Xu430ef402016-10-14 17:22:23 +08006933 }
John Kessenich149afc32018-08-14 13:31:43 -06006934 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6935 spvGroupOperands.push_back(scope);
6936 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006937 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006938 spvGroupOperands.push_back(groupOp);
6939 }
Rex Xu51596642016-09-21 18:56:12 +08006940 }
6941
John Kessenich149afc32018-08-14 13:31:43 -06006942 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6943 spv::IdImmediate op = { true, *opIt };
6944 spvGroupOperands.push_back(op);
6945 }
John Kessenich91cef522016-05-05 16:45:40 -06006946
6947 switch (op) {
6948 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006949 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006950 break;
John Kessenich91cef522016-05-05 16:45:40 -06006951 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006952 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006953 break;
John Kessenich91cef522016-05-05 16:45:40 -06006954 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006955 opCode = spv::OpSubgroupAllEqualKHR;
6956 break;
Rex Xu51596642016-09-21 18:56:12 +08006957 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006958 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006959 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006960 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006961 break;
6962 case glslang::EOpReadFirstInvocation:
6963 opCode = spv::OpSubgroupFirstInvocationKHR;
6964 break;
6965 case glslang::EOpBallot:
6966 {
6967 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6968 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6969 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6970 //
6971 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6972 //
6973 spv::Id uintType = builder.makeUintType(32);
6974 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6975 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6976
6977 std::vector<spv::Id> components;
6978 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6979 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6980
6981 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6982 return builder.createUnaryOp(spv::OpBitcast, typeId,
6983 builder.createCompositeConstruct(uvec2Type, components));
6984 }
6985
Rex Xu9d93a232016-05-05 12:30:44 +08006986 case glslang::EOpMinInvocations:
6987 case glslang::EOpMaxInvocations:
6988 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006989 case glslang::EOpMinInvocationsInclusiveScan:
6990 case glslang::EOpMaxInvocationsInclusiveScan:
6991 case glslang::EOpAddInvocationsInclusiveScan:
6992 case glslang::EOpMinInvocationsExclusiveScan:
6993 case glslang::EOpMaxInvocationsExclusiveScan:
6994 case glslang::EOpAddInvocationsExclusiveScan:
6995 if (op == glslang::EOpMinInvocations ||
6996 op == glslang::EOpMinInvocationsInclusiveScan ||
6997 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006998 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006999 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007000 else {
7001 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007002 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007003 else
Rex Xu51596642016-09-21 18:56:12 +08007004 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007005 }
Rex Xu430ef402016-10-14 17:22:23 +08007006 } else if (op == glslang::EOpMaxInvocations ||
7007 op == glslang::EOpMaxInvocationsInclusiveScan ||
7008 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007009 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007010 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007011 else {
7012 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007013 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007014 else
Rex Xu51596642016-09-21 18:56:12 +08007015 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007016 }
7017 } else {
7018 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007019 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007020 else
Rex Xu51596642016-09-21 18:56:12 +08007021 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007022 }
7023
Rex Xu2bbbe062016-08-23 15:41:05 +08007024 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007025 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007026
7027 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007028 case glslang::EOpMinInvocationsNonUniform:
7029 case glslang::EOpMaxInvocationsNonUniform:
7030 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007031 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7032 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7033 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7034 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7035 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7036 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7037 if (op == glslang::EOpMinInvocationsNonUniform ||
7038 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7039 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007040 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007041 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007042 else {
7043 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007044 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007045 else
Rex Xu51596642016-09-21 18:56:12 +08007046 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007047 }
7048 }
Rex Xu430ef402016-10-14 17:22:23 +08007049 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7050 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7051 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007052 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007053 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007054 else {
7055 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007056 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007057 else
Rex Xu51596642016-09-21 18:56:12 +08007058 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007059 }
7060 }
7061 else {
7062 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007063 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007064 else
Rex Xu51596642016-09-21 18:56:12 +08007065 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007066 }
7067
Rex Xu2bbbe062016-08-23 15:41:05 +08007068 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007069 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007070
7071 break;
John Kessenich91cef522016-05-05 16:45:40 -06007072 default:
7073 logger->missingFunctionality("invocation operation");
7074 return spv::NoResult;
7075 }
Rex Xu51596642016-09-21 18:56:12 +08007076
7077 assert(opCode != spv::OpNop);
7078 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007079}
7080
Rex Xu2bbbe062016-08-23 15:41:05 +08007081// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007082spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7083 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007084{
7085 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7086 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007087 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007088 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007089 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7090 op == spv::OpGroupSMinNonUniformAMD ||
7091 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7092 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007093 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7094
7095 // Handle group invocation operations scalar by scalar.
7096 // The result type is the same type as the original type.
7097 // The algorithm is to:
7098 // - break the vector into scalars
7099 // - apply the operation to each scalar
7100 // - make a vector out the scalar results
7101
7102 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007103 int numComponents = builder.getNumComponents(operands[0]);
7104 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007105 std::vector<spv::Id> results;
7106
7107 // do each scalar op
7108 for (int comp = 0; comp < numComponents; ++comp) {
7109 std::vector<unsigned int> indexes;
7110 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007111 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7112 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007113 if (op == spv::OpSubgroupReadInvocationKHR) {
7114 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007115 spv::IdImmediate operand = { true, operands[1] };
7116 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007117 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007118 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7119 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007120 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007121 spv::IdImmediate operand = { true, operands[1] };
7122 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007123 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007124 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7125 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007126 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007127 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007128 spvGroupOperands.push_back(scalar);
7129 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007130
Rex Xub7072052016-09-26 15:53:40 +08007131 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007132 }
7133
7134 // put the pieces together
7135 return builder.createCompositeConstruct(typeId, results);
7136}
Rex Xu2bbbe062016-08-23 15:41:05 +08007137
John Kessenich66011cb2018-03-06 16:12:04 -07007138// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007139spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7140 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007141{
7142 // Add the required capabilities.
7143 switch (op) {
7144 case glslang::EOpSubgroupElect:
7145 builder.addCapability(spv::CapabilityGroupNonUniform);
7146 break;
7147 case glslang::EOpSubgroupAll:
7148 case glslang::EOpSubgroupAny:
7149 case glslang::EOpSubgroupAllEqual:
7150 builder.addCapability(spv::CapabilityGroupNonUniform);
7151 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7152 break;
7153 case glslang::EOpSubgroupBroadcast:
7154 case glslang::EOpSubgroupBroadcastFirst:
7155 case glslang::EOpSubgroupBallot:
7156 case glslang::EOpSubgroupInverseBallot:
7157 case glslang::EOpSubgroupBallotBitExtract:
7158 case glslang::EOpSubgroupBallotBitCount:
7159 case glslang::EOpSubgroupBallotInclusiveBitCount:
7160 case glslang::EOpSubgroupBallotExclusiveBitCount:
7161 case glslang::EOpSubgroupBallotFindLSB:
7162 case glslang::EOpSubgroupBallotFindMSB:
7163 builder.addCapability(spv::CapabilityGroupNonUniform);
7164 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7165 break;
7166 case glslang::EOpSubgroupShuffle:
7167 case glslang::EOpSubgroupShuffleXor:
7168 builder.addCapability(spv::CapabilityGroupNonUniform);
7169 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7170 break;
7171 case glslang::EOpSubgroupShuffleUp:
7172 case glslang::EOpSubgroupShuffleDown:
7173 builder.addCapability(spv::CapabilityGroupNonUniform);
7174 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7175 break;
7176 case glslang::EOpSubgroupAdd:
7177 case glslang::EOpSubgroupMul:
7178 case glslang::EOpSubgroupMin:
7179 case glslang::EOpSubgroupMax:
7180 case glslang::EOpSubgroupAnd:
7181 case glslang::EOpSubgroupOr:
7182 case glslang::EOpSubgroupXor:
7183 case glslang::EOpSubgroupInclusiveAdd:
7184 case glslang::EOpSubgroupInclusiveMul:
7185 case glslang::EOpSubgroupInclusiveMin:
7186 case glslang::EOpSubgroupInclusiveMax:
7187 case glslang::EOpSubgroupInclusiveAnd:
7188 case glslang::EOpSubgroupInclusiveOr:
7189 case glslang::EOpSubgroupInclusiveXor:
7190 case glslang::EOpSubgroupExclusiveAdd:
7191 case glslang::EOpSubgroupExclusiveMul:
7192 case glslang::EOpSubgroupExclusiveMin:
7193 case glslang::EOpSubgroupExclusiveMax:
7194 case glslang::EOpSubgroupExclusiveAnd:
7195 case glslang::EOpSubgroupExclusiveOr:
7196 case glslang::EOpSubgroupExclusiveXor:
7197 builder.addCapability(spv::CapabilityGroupNonUniform);
7198 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7199 break;
7200 case glslang::EOpSubgroupClusteredAdd:
7201 case glslang::EOpSubgroupClusteredMul:
7202 case glslang::EOpSubgroupClusteredMin:
7203 case glslang::EOpSubgroupClusteredMax:
7204 case glslang::EOpSubgroupClusteredAnd:
7205 case glslang::EOpSubgroupClusteredOr:
7206 case glslang::EOpSubgroupClusteredXor:
7207 builder.addCapability(spv::CapabilityGroupNonUniform);
7208 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7209 break;
7210 case glslang::EOpSubgroupQuadBroadcast:
7211 case glslang::EOpSubgroupQuadSwapHorizontal:
7212 case glslang::EOpSubgroupQuadSwapVertical:
7213 case glslang::EOpSubgroupQuadSwapDiagonal:
7214 builder.addCapability(spv::CapabilityGroupNonUniform);
7215 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7216 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007217 case glslang::EOpSubgroupPartitionedAdd:
7218 case glslang::EOpSubgroupPartitionedMul:
7219 case glslang::EOpSubgroupPartitionedMin:
7220 case glslang::EOpSubgroupPartitionedMax:
7221 case glslang::EOpSubgroupPartitionedAnd:
7222 case glslang::EOpSubgroupPartitionedOr:
7223 case glslang::EOpSubgroupPartitionedXor:
7224 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7225 case glslang::EOpSubgroupPartitionedInclusiveMul:
7226 case glslang::EOpSubgroupPartitionedInclusiveMin:
7227 case glslang::EOpSubgroupPartitionedInclusiveMax:
7228 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7229 case glslang::EOpSubgroupPartitionedInclusiveOr:
7230 case glslang::EOpSubgroupPartitionedInclusiveXor:
7231 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7232 case glslang::EOpSubgroupPartitionedExclusiveMul:
7233 case glslang::EOpSubgroupPartitionedExclusiveMin:
7234 case glslang::EOpSubgroupPartitionedExclusiveMax:
7235 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7236 case glslang::EOpSubgroupPartitionedExclusiveOr:
7237 case glslang::EOpSubgroupPartitionedExclusiveXor:
7238 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7239 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7240 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007241 default: assert(0 && "Unhandled subgroup operation!");
7242 }
7243
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007244
7245 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7246 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007247 const bool isBool = typeProxy == glslang::EbtBool;
7248
7249 spv::Op opCode = spv::OpNop;
7250
7251 // Figure out which opcode to use.
7252 switch (op) {
7253 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7254 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7255 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7256 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7257 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7258 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7259 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7260 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7261 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7262 case glslang::EOpSubgroupBallotBitCount:
7263 case glslang::EOpSubgroupBallotInclusiveBitCount:
7264 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7265 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7266 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7267 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7268 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7269 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7270 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7271 case glslang::EOpSubgroupAdd:
7272 case glslang::EOpSubgroupInclusiveAdd:
7273 case glslang::EOpSubgroupExclusiveAdd:
7274 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007275 case glslang::EOpSubgroupPartitionedAdd:
7276 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7277 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007278 if (isFloat) {
7279 opCode = spv::OpGroupNonUniformFAdd;
7280 } else {
7281 opCode = spv::OpGroupNonUniformIAdd;
7282 }
7283 break;
7284 case glslang::EOpSubgroupMul:
7285 case glslang::EOpSubgroupInclusiveMul:
7286 case glslang::EOpSubgroupExclusiveMul:
7287 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007288 case glslang::EOpSubgroupPartitionedMul:
7289 case glslang::EOpSubgroupPartitionedInclusiveMul:
7290 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007291 if (isFloat) {
7292 opCode = spv::OpGroupNonUniformFMul;
7293 } else {
7294 opCode = spv::OpGroupNonUniformIMul;
7295 }
7296 break;
7297 case glslang::EOpSubgroupMin:
7298 case glslang::EOpSubgroupInclusiveMin:
7299 case glslang::EOpSubgroupExclusiveMin:
7300 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007301 case glslang::EOpSubgroupPartitionedMin:
7302 case glslang::EOpSubgroupPartitionedInclusiveMin:
7303 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007304 if (isFloat) {
7305 opCode = spv::OpGroupNonUniformFMin;
7306 } else if (isUnsigned) {
7307 opCode = spv::OpGroupNonUniformUMin;
7308 } else {
7309 opCode = spv::OpGroupNonUniformSMin;
7310 }
7311 break;
7312 case glslang::EOpSubgroupMax:
7313 case glslang::EOpSubgroupInclusiveMax:
7314 case glslang::EOpSubgroupExclusiveMax:
7315 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007316 case glslang::EOpSubgroupPartitionedMax:
7317 case glslang::EOpSubgroupPartitionedInclusiveMax:
7318 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007319 if (isFloat) {
7320 opCode = spv::OpGroupNonUniformFMax;
7321 } else if (isUnsigned) {
7322 opCode = spv::OpGroupNonUniformUMax;
7323 } else {
7324 opCode = spv::OpGroupNonUniformSMax;
7325 }
7326 break;
7327 case glslang::EOpSubgroupAnd:
7328 case glslang::EOpSubgroupInclusiveAnd:
7329 case glslang::EOpSubgroupExclusiveAnd:
7330 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007331 case glslang::EOpSubgroupPartitionedAnd:
7332 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7333 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007334 if (isBool) {
7335 opCode = spv::OpGroupNonUniformLogicalAnd;
7336 } else {
7337 opCode = spv::OpGroupNonUniformBitwiseAnd;
7338 }
7339 break;
7340 case glslang::EOpSubgroupOr:
7341 case glslang::EOpSubgroupInclusiveOr:
7342 case glslang::EOpSubgroupExclusiveOr:
7343 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007344 case glslang::EOpSubgroupPartitionedOr:
7345 case glslang::EOpSubgroupPartitionedInclusiveOr:
7346 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007347 if (isBool) {
7348 opCode = spv::OpGroupNonUniformLogicalOr;
7349 } else {
7350 opCode = spv::OpGroupNonUniformBitwiseOr;
7351 }
7352 break;
7353 case glslang::EOpSubgroupXor:
7354 case glslang::EOpSubgroupInclusiveXor:
7355 case glslang::EOpSubgroupExclusiveXor:
7356 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007357 case glslang::EOpSubgroupPartitionedXor:
7358 case glslang::EOpSubgroupPartitionedInclusiveXor:
7359 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007360 if (isBool) {
7361 opCode = spv::OpGroupNonUniformLogicalXor;
7362 } else {
7363 opCode = spv::OpGroupNonUniformBitwiseXor;
7364 }
7365 break;
7366 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7367 case glslang::EOpSubgroupQuadSwapHorizontal:
7368 case glslang::EOpSubgroupQuadSwapVertical:
7369 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7370 default: assert(0 && "Unhandled subgroup operation!");
7371 }
7372
John Kessenich149afc32018-08-14 13:31:43 -06007373 // get the right Group Operation
7374 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007375 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007376 default:
7377 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007378 case glslang::EOpSubgroupBallotBitCount:
7379 case glslang::EOpSubgroupAdd:
7380 case glslang::EOpSubgroupMul:
7381 case glslang::EOpSubgroupMin:
7382 case glslang::EOpSubgroupMax:
7383 case glslang::EOpSubgroupAnd:
7384 case glslang::EOpSubgroupOr:
7385 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007386 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007387 break;
7388 case glslang::EOpSubgroupBallotInclusiveBitCount:
7389 case glslang::EOpSubgroupInclusiveAdd:
7390 case glslang::EOpSubgroupInclusiveMul:
7391 case glslang::EOpSubgroupInclusiveMin:
7392 case glslang::EOpSubgroupInclusiveMax:
7393 case glslang::EOpSubgroupInclusiveAnd:
7394 case glslang::EOpSubgroupInclusiveOr:
7395 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007396 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007397 break;
7398 case glslang::EOpSubgroupBallotExclusiveBitCount:
7399 case glslang::EOpSubgroupExclusiveAdd:
7400 case glslang::EOpSubgroupExclusiveMul:
7401 case glslang::EOpSubgroupExclusiveMin:
7402 case glslang::EOpSubgroupExclusiveMax:
7403 case glslang::EOpSubgroupExclusiveAnd:
7404 case glslang::EOpSubgroupExclusiveOr:
7405 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007406 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007407 break;
7408 case glslang::EOpSubgroupClusteredAdd:
7409 case glslang::EOpSubgroupClusteredMul:
7410 case glslang::EOpSubgroupClusteredMin:
7411 case glslang::EOpSubgroupClusteredMax:
7412 case glslang::EOpSubgroupClusteredAnd:
7413 case glslang::EOpSubgroupClusteredOr:
7414 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007415 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007416 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007417 case glslang::EOpSubgroupPartitionedAdd:
7418 case glslang::EOpSubgroupPartitionedMul:
7419 case glslang::EOpSubgroupPartitionedMin:
7420 case glslang::EOpSubgroupPartitionedMax:
7421 case glslang::EOpSubgroupPartitionedAnd:
7422 case glslang::EOpSubgroupPartitionedOr:
7423 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007424 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007425 break;
7426 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7427 case glslang::EOpSubgroupPartitionedInclusiveMul:
7428 case glslang::EOpSubgroupPartitionedInclusiveMin:
7429 case glslang::EOpSubgroupPartitionedInclusiveMax:
7430 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7431 case glslang::EOpSubgroupPartitionedInclusiveOr:
7432 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007433 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007434 break;
7435 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7436 case glslang::EOpSubgroupPartitionedExclusiveMul:
7437 case glslang::EOpSubgroupPartitionedExclusiveMin:
7438 case glslang::EOpSubgroupPartitionedExclusiveMax:
7439 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7440 case glslang::EOpSubgroupPartitionedExclusiveOr:
7441 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007442 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007443 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007444 }
7445
John Kessenich149afc32018-08-14 13:31:43 -06007446 // build the instruction
7447 std::vector<spv::IdImmediate> spvGroupOperands;
7448
7449 // Every operation begins with the Execution Scope operand.
7450 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7451 spvGroupOperands.push_back(executionScope);
7452
7453 // Next, for all operations that use a Group Operation, push that as an operand.
7454 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007455 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007456 spvGroupOperands.push_back(groupOperand);
7457 }
7458
John Kessenich66011cb2018-03-06 16:12:04 -07007459 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007460 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7461 spv::IdImmediate operand = { true, *opIt };
7462 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007463 }
7464
7465 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007466 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007467 switch (op) {
7468 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007469 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7470 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7471 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7472 }
7473 if (directionId != spv::NoResult) {
7474 spv::IdImmediate direction = { true, directionId };
7475 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007476 }
7477
7478 return builder.createOp(opCode, typeId, spvGroupOperands);
7479}
7480
John Kessenich8985fc92020-03-03 10:25:07 -07007481spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7482 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007483{
John Kessenich66011cb2018-03-06 16:12:04 -07007484 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7485 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007486
John Kessenich140f3df2015-06-26 16:58:36 -06007487 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007488 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007489 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007490 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007491 spv::Id typeId0 = 0;
7492 if (consumedOperands > 0)
7493 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007494 spv::Id typeId1 = 0;
7495 if (consumedOperands > 1)
7496 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007497 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007498
7499 switch (op) {
7500 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007501 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007502 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007503 else if (isUnsigned)
7504 libCall = spv::GLSLstd450UMin;
7505 else
7506 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007507 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007508 break;
7509 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007510 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007511 break;
7512 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007513 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007514 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007515 else if (isUnsigned)
7516 libCall = spv::GLSLstd450UMax;
7517 else
7518 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007519 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007520 break;
7521 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007522 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007523 break;
7524 case glslang::EOpDot:
7525 opCode = spv::OpDot;
7526 break;
7527 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007528 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007529 break;
7530
7531 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007532 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007533 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007534 else if (isUnsigned)
7535 libCall = spv::GLSLstd450UClamp;
7536 else
7537 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007538 builder.promoteScalar(precision, operands.front(), operands[1]);
7539 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007540 break;
7541 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007542 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7543 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007544 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007545 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007546 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007547 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007548 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007549 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007550 break;
7551 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007552 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007553 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007554 break;
7555 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007556 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007557 builder.promoteScalar(precision, operands[0], operands[2]);
7558 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007559 break;
7560
7561 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007562 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007563 break;
7564 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007565 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007566 break;
7567 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007568 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007569 break;
7570 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007571 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007572 break;
7573 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007574 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007575 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007576 case glslang::EOpBarrier:
7577 {
7578 // This is for the extended controlBarrier function, with four operands.
7579 // The unextended barrier() goes through createNoArgOperation.
7580 assert(operands.size() == 4);
7581 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7582 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7583 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007584 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7585 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007586 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7587 spv::MemorySemanticsMakeVisibleKHRMask |
7588 spv::MemorySemanticsOutputMemoryKHRMask |
7589 spv::MemorySemanticsVolatileMask)) {
7590 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7591 }
John Kessenich8985fc92020-03-03 10:25:07 -07007592 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7593 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007594 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7595 }
7596 return 0;
7597 }
7598 break;
7599 case glslang::EOpMemoryBarrier:
7600 {
7601 // This is for the extended memoryBarrier function, with three operands.
7602 // The unextended memoryBarrier() goes through createNoArgOperation.
7603 assert(operands.size() == 3);
7604 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7605 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7606 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7607 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7608 spv::MemorySemanticsMakeVisibleKHRMask |
7609 spv::MemorySemanticsOutputMemoryKHRMask |
7610 spv::MemorySemanticsVolatileMask)) {
7611 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7612 }
7613 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7614 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7615 }
7616 return 0;
7617 }
7618 break;
7619
John Kessenicha28f7a72019-08-06 07:00:58 -06007620#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007621 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007622 if (typeProxy == glslang::EbtFloat16)
7623 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007624 libCall = spv::GLSLstd450InterpolateAtSample;
7625 break;
7626 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007627 if (typeProxy == glslang::EbtFloat16)
7628 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007629 libCall = spv::GLSLstd450InterpolateAtOffset;
7630 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007631 case glslang::EOpAddCarry:
7632 opCode = spv::OpIAddCarry;
7633 typeId = builder.makeStructResultType(typeId0, typeId0);
7634 consumedOperands = 2;
7635 break;
7636 case glslang::EOpSubBorrow:
7637 opCode = spv::OpISubBorrow;
7638 typeId = builder.makeStructResultType(typeId0, typeId0);
7639 consumedOperands = 2;
7640 break;
7641 case glslang::EOpUMulExtended:
7642 opCode = spv::OpUMulExtended;
7643 typeId = builder.makeStructResultType(typeId0, typeId0);
7644 consumedOperands = 2;
7645 break;
7646 case glslang::EOpIMulExtended:
7647 opCode = spv::OpSMulExtended;
7648 typeId = builder.makeStructResultType(typeId0, typeId0);
7649 consumedOperands = 2;
7650 break;
7651 case glslang::EOpBitfieldExtract:
7652 if (isUnsigned)
7653 opCode = spv::OpBitFieldUExtract;
7654 else
7655 opCode = spv::OpBitFieldSExtract;
7656 break;
7657 case glslang::EOpBitfieldInsert:
7658 opCode = spv::OpBitFieldInsert;
7659 break;
7660
7661 case glslang::EOpFma:
7662 libCall = spv::GLSLstd450Fma;
7663 break;
7664 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007665 {
7666 libCall = spv::GLSLstd450FrexpStruct;
7667 assert(builder.isPointerType(typeId1));
7668 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007669 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007670 if (width == 16)
7671 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7672 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007673 if (builder.getNumComponents(operands[0]) == 1)
7674 frexpIntType = builder.makeIntegerType(width, true);
7675 else
John Kessenich8985fc92020-03-03 10:25:07 -07007676 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7677 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007678 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7679 consumedOperands = 1;
7680 }
John Kessenich55e7d112015-11-15 21:33:39 -07007681 break;
7682 case glslang::EOpLdexp:
7683 libCall = spv::GLSLstd450Ldexp;
7684 break;
7685
Rex Xu574ab042016-04-14 16:53:07 +08007686 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007687 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007688
John Kessenich66011cb2018-03-06 16:12:04 -07007689 case glslang::EOpSubgroupBroadcast:
7690 case glslang::EOpSubgroupBallotBitExtract:
7691 case glslang::EOpSubgroupShuffle:
7692 case glslang::EOpSubgroupShuffleXor:
7693 case glslang::EOpSubgroupShuffleUp:
7694 case glslang::EOpSubgroupShuffleDown:
7695 case glslang::EOpSubgroupClusteredAdd:
7696 case glslang::EOpSubgroupClusteredMul:
7697 case glslang::EOpSubgroupClusteredMin:
7698 case glslang::EOpSubgroupClusteredMax:
7699 case glslang::EOpSubgroupClusteredAnd:
7700 case glslang::EOpSubgroupClusteredOr:
7701 case glslang::EOpSubgroupClusteredXor:
7702 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007703 case glslang::EOpSubgroupPartitionedAdd:
7704 case glslang::EOpSubgroupPartitionedMul:
7705 case glslang::EOpSubgroupPartitionedMin:
7706 case glslang::EOpSubgroupPartitionedMax:
7707 case glslang::EOpSubgroupPartitionedAnd:
7708 case glslang::EOpSubgroupPartitionedOr:
7709 case glslang::EOpSubgroupPartitionedXor:
7710 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7711 case glslang::EOpSubgroupPartitionedInclusiveMul:
7712 case glslang::EOpSubgroupPartitionedInclusiveMin:
7713 case glslang::EOpSubgroupPartitionedInclusiveMax:
7714 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7715 case glslang::EOpSubgroupPartitionedInclusiveOr:
7716 case glslang::EOpSubgroupPartitionedInclusiveXor:
7717 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7718 case glslang::EOpSubgroupPartitionedExclusiveMul:
7719 case glslang::EOpSubgroupPartitionedExclusiveMin:
7720 case glslang::EOpSubgroupPartitionedExclusiveMax:
7721 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7722 case glslang::EOpSubgroupPartitionedExclusiveOr:
7723 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007724 return createSubgroupOperation(op, typeId, operands, typeProxy);
7725
Rex Xu9d93a232016-05-05 12:30:44 +08007726 case glslang::EOpSwizzleInvocations:
7727 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7728 libCall = spv::SwizzleInvocationsAMD;
7729 break;
7730 case glslang::EOpSwizzleInvocationsMasked:
7731 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7732 libCall = spv::SwizzleInvocationsMaskedAMD;
7733 break;
7734 case glslang::EOpWriteInvocation:
7735 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7736 libCall = spv::WriteInvocationAMD;
7737 break;
7738
7739 case glslang::EOpMin3:
7740 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7741 if (isFloat)
7742 libCall = spv::FMin3AMD;
7743 else {
7744 if (isUnsigned)
7745 libCall = spv::UMin3AMD;
7746 else
7747 libCall = spv::SMin3AMD;
7748 }
7749 break;
7750 case glslang::EOpMax3:
7751 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7752 if (isFloat)
7753 libCall = spv::FMax3AMD;
7754 else {
7755 if (isUnsigned)
7756 libCall = spv::UMax3AMD;
7757 else
7758 libCall = spv::SMax3AMD;
7759 }
7760 break;
7761 case glslang::EOpMid3:
7762 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7763 if (isFloat)
7764 libCall = spv::FMid3AMD;
7765 else {
7766 if (isUnsigned)
7767 libCall = spv::UMid3AMD;
7768 else
7769 libCall = spv::SMid3AMD;
7770 }
7771 break;
7772
7773 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007774 if (typeProxy == glslang::EbtFloat16)
7775 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007776 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7777 libCall = spv::InterpolateAtVertexAMD;
7778 break;
Chao Chen3c366992018-09-19 11:41:59 -07007779
Daniel Kochdb32b242020-03-17 20:42:47 -04007780 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007781 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007782 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007783 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007784 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007785 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007786 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007787 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007788 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007789 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007790
7791 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007792 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7793 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007794 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007795 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7796 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007797 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007798 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7799 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007800 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007801 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7802 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007803 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007804 typeId = builder.makeBoolType();
7805 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007806 break;
7807 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007808 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007809 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007810 break;
7811 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007812 typeId = builder.makeFloatType(32);
7813 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007814 break;
7815 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007816 typeId = builder.makeIntType(32);
7817 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007818 break;
7819 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007820 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007821 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007822 break;
7823 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007824 typeId = builder.makeIntType(32);
7825 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007826 break;
7827 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007828 typeId = builder.makeIntType(32);
7829 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007830 break;
7831 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007832 typeId = builder.makeIntType(32);
7833 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007834 break;
7835 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007836 typeId = builder.makeIntType(32);
7837 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007838 break;
7839 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007840 typeId = builder.makeIntType(32);
7841 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007842 break;
7843 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007844 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7845 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007846 break;
7847 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007848 typeId = builder.makeBoolType();
7849 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007850 break;
7851 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007852 typeId = builder.makeBoolType();
7853 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007854 break;
7855 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007856 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7857 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007858 break;
7859 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007860 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7861 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007862 break;
7863 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007864 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7865 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007866 break;
7867 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007868 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7869 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007870 break;
7871 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007872 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007873 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007874 break;
7875 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007876 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007877 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007878 break;
Chao Chen3c366992018-09-19 11:41:59 -07007879 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7880 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7881 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007882 case glslang::EOpCooperativeMatrixMulAdd:
7883 opCode = spv::OpCooperativeMatrixMulAddNV;
7884 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007885#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007886 default:
7887 return 0;
7888 }
7889
7890 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007891 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007892 // Use an extended instruction from the standard library.
7893 // Construct the call arguments, without modifying the original operands vector.
7894 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7895 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007896 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007897 } else if (opCode == spv::OpDot && !isFloat) {
7898 // int dot(int, int)
7899 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7900 const int componentCount = builder.getNumComponents(operands[0]);
7901 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7902 builder.setPrecision(mulOp, precision);
7903 id = builder.createCompositeExtract(mulOp, typeId, 0);
7904 for (int i = 1; i < componentCount; ++i) {
7905 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007906 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007907 }
John Kessenich2359bd02015-12-06 19:29:11 -07007908 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007909 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007910 case 0:
7911 // should all be handled by visitAggregate and createNoArgOperation
7912 assert(0);
7913 return 0;
7914 case 1:
7915 // should all be handled by createUnaryOperation
7916 assert(0);
7917 return 0;
7918 case 2:
7919 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7920 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007921 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007922 // anything 3 or over doesn't have l-value operands, so all should be consumed
7923 assert(consumedOperands == operands.size());
7924 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007925 break;
7926 }
7927 }
7928
John Kessenichb9197c82019-08-11 07:41:45 -06007929#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007930 // Decode the return types that were structures
7931 switch (op) {
7932 case glslang::EOpAddCarry:
7933 case glslang::EOpSubBorrow:
7934 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7935 id = builder.createCompositeExtract(id, typeId0, 0);
7936 break;
7937 case glslang::EOpUMulExtended:
7938 case glslang::EOpIMulExtended:
7939 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7940 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7941 break;
7942 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007943 {
7944 assert(operands.size() == 2);
7945 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7946 // "exp" is floating-point type (from HLSL intrinsic)
7947 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7948 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7949 builder.createStore(member1, operands[1]);
7950 } else
7951 // "exp" is integer type (from GLSL built-in function)
7952 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7953 id = builder.createCompositeExtract(id, typeId0, 0);
7954 }
John Kessenich55e7d112015-11-15 21:33:39 -07007955 break;
7956 default:
7957 break;
7958 }
John Kessenichb9197c82019-08-11 07:41:45 -06007959#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007960
John Kessenich32cfd492016-02-02 12:37:46 -07007961 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007962}
7963
Rex Xu9d93a232016-05-05 12:30:44 +08007964// Intrinsics with no arguments (or no return value, and no precision).
7965spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007966{
Jeff Bolz36831c92018-09-05 10:11:41 -05007967 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007968 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7969 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007970
7971 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007972 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007973 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007974 if (glslangIntermediate->usingVulkanMemoryModel()) {
7975 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7976 spv::MemorySemanticsOutputMemoryKHRMask |
7977 spv::MemorySemanticsAcquireReleaseMask);
7978 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7979 } else {
7980 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7981 }
John Kessenich82979362017-12-11 04:02:24 -07007982 } else {
7983 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7984 spv::MemorySemanticsWorkgroupMemoryMask |
7985 spv::MemorySemanticsAcquireReleaseMask);
7986 }
John Kessenich140f3df2015-06-26 16:58:36 -06007987 return 0;
7988 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007989 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7990 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007991 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007992 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007993 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7994 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007995 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007996 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007997 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7998 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007999 return 0;
8000 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008001 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
8002 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008003 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06008004#ifndef GLSLANG_WEB
8005 case glslang::EOpMemoryBarrierAtomicCounter:
8006 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
8007 spv::MemorySemanticsAcquireReleaseMask);
8008 return 0;
8009 case glslang::EOpMemoryBarrierImage:
8010 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8011 spv::MemorySemanticsAcquireReleaseMask);
8012 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008013 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008014 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008015 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008016 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008017 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008018 case glslang::EOpDeviceMemoryBarrier:
8019 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8020 spv::MemorySemanticsImageMemoryMask |
8021 spv::MemorySemanticsAcquireReleaseMask);
8022 return 0;
8023 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8024 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8025 spv::MemorySemanticsImageMemoryMask |
8026 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008027 return 0;
8028 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008029 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8030 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008031 return 0;
8032 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008033 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8034 spv::MemorySemanticsWorkgroupMemoryMask |
8035 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008036 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008037 case glslang::EOpSubgroupBarrier:
8038 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8039 spv::MemorySemanticsAcquireReleaseMask);
8040 return spv::NoResult;
8041 case glslang::EOpSubgroupMemoryBarrier:
8042 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8043 spv::MemorySemanticsAcquireReleaseMask);
8044 return spv::NoResult;
8045 case glslang::EOpSubgroupMemoryBarrierBuffer:
8046 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8047 spv::MemorySemanticsAcquireReleaseMask);
8048 return spv::NoResult;
8049 case glslang::EOpSubgroupMemoryBarrierImage:
8050 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8051 spv::MemorySemanticsAcquireReleaseMask);
8052 return spv::NoResult;
8053 case glslang::EOpSubgroupMemoryBarrierShared:
8054 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8055 spv::MemorySemanticsAcquireReleaseMask);
8056 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008057
8058 case glslang::EOpEmitVertex:
8059 builder.createNoResultOp(spv::OpEmitVertex);
8060 return 0;
8061 case glslang::EOpEndPrimitive:
8062 builder.createNoResultOp(spv::OpEndPrimitive);
8063 return 0;
8064
John Kessenich66011cb2018-03-06 16:12:04 -07008065 case glslang::EOpSubgroupElect: {
8066 std::vector<spv::Id> operands;
8067 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8068 }
Rex Xu9d93a232016-05-05 12:30:44 +08008069 case glslang::EOpTime:
8070 {
8071 std::vector<spv::Id> args; // Dummy arguments
8072 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8073 return builder.setPrecision(id, precision);
8074 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008075 case glslang::EOpIgnoreIntersection:
8076 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008077 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008078 case glslang::EOpTerminateRay:
8079 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008080 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008081 case glslang::EOpRayQueryInitialize:
8082 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8083 return 0;
8084 case glslang::EOpRayQueryTerminate:
8085 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8086 return 0;
8087 case glslang::EOpRayQueryGenerateIntersection:
8088 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8089 return 0;
8090 case glslang::EOpRayQueryConfirmIntersection:
8091 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8092 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008093 case glslang::EOpBeginInvocationInterlock:
8094 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8095 return 0;
8096 case glslang::EOpEndInvocationInterlock:
8097 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8098 return 0;
8099
Jeff Bolzba6170b2019-07-01 09:23:23 -05008100 case glslang::EOpIsHelperInvocation:
8101 {
8102 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008103 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8104 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8105 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008106 }
8107
amhagan91fb0092019-07-10 21:14:38 -04008108 case glslang::EOpReadClockSubgroupKHR: {
8109 std::vector<spv::Id> args;
8110 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8111 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8112 builder.addCapability(spv::CapabilityShaderClockKHR);
8113 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8114 }
8115
8116 case glslang::EOpReadClockDeviceKHR: {
8117 std::vector<spv::Id> args;
8118 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8119 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8120 builder.addCapability(spv::CapabilityShaderClockKHR);
8121 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8122 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008123#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008124 default:
John Kessenich155d3512019-08-08 23:29:20 -06008125 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008126 }
John Kessenich155d3512019-08-08 23:29:20 -06008127
8128 logger->missingFunctionality("unknown operation with no arguments");
8129
8130 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008131}
8132
8133spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8134{
John Kessenich2f273362015-07-18 22:34:27 -06008135 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008136 spv::Id id;
8137 if (symbolValues.end() != iter) {
8138 id = iter->second;
8139 return id;
8140 }
8141
8142 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008143 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008144 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008145 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008146 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008147 if (forcedType.second != spv::NoType)
8148 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008149
Rex Xuc884b4a2016-06-29 15:03:44 +08008150 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008151 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8152 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8153 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008154#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008155 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008156 if (symbol->getQualifier().hasComponent())
8157 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8158 if (symbol->getQualifier().hasIndex())
8159 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008160#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008161 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008162 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008163 // atomic counters use this:
8164 if (symbol->getQualifier().hasOffset())
8165 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008166 }
8167
scygan2c864272016-05-18 18:09:17 +02008168 if (symbol->getQualifier().hasLocation())
8169 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008170 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008171 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008172 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008173 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008174 }
John Kessenich140f3df2015-06-26 16:58:36 -06008175 if (symbol->getQualifier().hasSet())
8176 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008177 else if (IsDescriptorResource(symbol->getType())) {
8178 // default to 0
8179 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8180 }
John Kessenich140f3df2015-06-26 16:58:36 -06008181 if (symbol->getQualifier().hasBinding())
8182 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008183 else if (IsDescriptorResource(symbol->getType())) {
8184 // default to 0
8185 builder.addDecoration(id, spv::DecorationBinding, 0);
8186 }
John Kessenich6c292d32016-02-15 20:58:50 -07008187 if (symbol->getQualifier().hasAttachment())
8188 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008189 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008190 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008191 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008192 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008193 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8194 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8195 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8196 }
8197 if (symbol->getQualifier().hasXfbOffset())
8198 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008199 }
8200
John Kessenichb9197c82019-08-11 07:41:45 -06008201 // add built-in variable decoration
8202 if (builtIn != spv::BuiltInMax) {
8203 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8204 }
8205
8206#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008207 if (symbol->getType().isImage()) {
8208 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008209 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8210 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008211 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008212 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008213 }
8214
John Kessenich5611c6d2018-04-05 11:25:02 -06008215 // nonuniform
8216 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8217
chaoc0ad6a4e2016-12-19 16:29:34 -08008218 if (builtIn == spv::BuiltInSampleMask) {
8219 spv::Decoration decoration;
8220 // GL_NV_sample_mask_override_coverage extension
8221 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008222 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008223 else
8224 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008225 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008226 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008227 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008228 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8229 }
8230 }
chaoc771d89f2017-01-13 01:10:53 -08008231 else if (builtIn == spv::BuiltInLayer) {
8232 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008233 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008234 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008235 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8236 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8237 }
John Kessenichb41bff62017-08-11 13:07:17 -06008238 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008239 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8240 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008241 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8242 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8243 }
8244 }
8245
chaoc6e5acae2016-12-20 13:28:52 -08008246 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008247 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008248 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008249 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8250 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008251 if (symbol->getQualifier().pervertexNV) {
8252 builder.addDecoration(id, spv::DecorationPerVertexNV);
8253 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8254 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8255 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008256
John Kessenich5d610ee2018-03-07 18:05:55 -07008257 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8258 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8259 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8260 symbol->getType().getQualifier().semanticName);
8261 }
8262
John Kessenich7015bd62019-08-01 03:28:08 -06008263 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008264 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8265 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008266 }
John Kessenichb9197c82019-08-11 07:41:45 -06008267#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008268
John Kessenich140f3df2015-06-26 16:58:36 -06008269 return id;
8270}
8271
John Kessenicha28f7a72019-08-06 07:00:58 -06008272#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008273// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8274void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8275{
8276 if (member >= 0) {
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.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008285 }
Chao Chen3c366992018-09-19 11:41:59 -07008286 if (qualifier.perViewNV)
8287 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8288 if (qualifier.perTaskNV)
8289 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8290 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008291 if (qualifier.perPrimitiveNV) {
8292 // Need to add capability/extension for fragment shader.
8293 // Mesh shader already adds this by default.
8294 if (glslangIntermediate->getStage() == EShLangFragment) {
8295 builder.addCapability(spv::CapabilityMeshShadingNV);
8296 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8297 }
Chao Chen3c366992018-09-19 11:41:59 -07008298 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008299 }
Chao Chen3c366992018-09-19 11:41:59 -07008300 if (qualifier.perViewNV)
8301 builder.addDecoration(id, spv::DecorationPerViewNV);
8302 if (qualifier.perTaskNV)
8303 builder.addDecoration(id, spv::DecorationPerTaskNV);
8304 }
8305}
8306#endif
8307
John Kessenich55e7d112015-11-15 21:33:39 -07008308// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008309// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008310//
8311// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8312//
8313// Recursively walk the nodes. The nodes form a tree whose leaves are
8314// regular constants, which themselves are trees that createSpvConstant()
8315// recursively walks. So, this function walks the "top" of the tree:
8316// - emit specialization constant-building instructions for specConstant
8317// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008318spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008319{
John Kessenich7cc0e282016-03-20 00:46:02 -06008320 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008321
qining4f4bb812016-04-03 23:55:17 -04008322 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008323 if (! node.getQualifier().specConstant) {
8324 // hand off to the non-spec-constant path
8325 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8326 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008327 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8328 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8329 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008330 }
8331
8332 // We now know we have a specialization constant to build
8333
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008334 // Extra capabilities may be needed.
8335 if (node.getType().contains8BitInt())
8336 builder.addCapability(spv::CapabilityInt8);
8337 if (node.getType().contains16BitFloat())
8338 builder.addCapability(spv::CapabilityFloat16);
8339 if (node.getType().contains16BitInt())
8340 builder.addCapability(spv::CapabilityInt16);
8341 if (node.getType().contains64BitInt())
8342 builder.addCapability(spv::CapabilityInt64);
8343 if (node.getType().containsDouble())
8344 builder.addCapability(spv::CapabilityFloat64);
8345
John Kessenichd94c0032016-05-30 19:29:40 -06008346 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008347 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8348 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8349 std::vector<spv::Id> dimConstId;
8350 for (int dim = 0; dim < 3; ++dim) {
8351 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8352 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008353 if (specConst) {
8354 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8355 glslangIntermediate->getLocalSizeSpecId(dim));
8356 }
qining4f4bb812016-04-03 23:55:17 -04008357 }
8358 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8359 }
8360
8361 // An AST node labelled as specialization constant should be a symbol node.
8362 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8363 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008364 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008365 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008366 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8367 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8368 // will set the builder into spec constant op instruction generating mode.
8369 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008370 result = accessChainLoad(sub_tree->getType());
8371 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008372 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008373 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008374 } else {
8375 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008376 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008377 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008378 builder.addName(result, sn->getName().c_str());
8379 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008380 }
qining4f4bb812016-04-03 23:55:17 -04008381
8382 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8383 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008384 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008385 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008386}
8387
John Kessenich140f3df2015-06-26 16:58:36 -06008388// Use 'consts' as the flattened glslang source of scalar constants to recursively
8389// build the aggregate SPIR-V constant.
8390//
8391// If there are not enough elements present in 'consts', 0 will be substituted;
8392// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8393//
John Kessenich8985fc92020-03-03 10:25:07 -07008394spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8395 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008396{
8397 // vector of constants for SPIR-V
8398 std::vector<spv::Id> spvConsts;
8399
8400 // Type is used for struct and array constants
8401 spv::Id typeId = convertGlslangToSpvType(glslangType);
8402
8403 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008404 glslang::TType elementType(glslangType, 0);
8405 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008406 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008407 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008408 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008409 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008410 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008411 } else if (glslangType.isCoopMat()) {
8412 glslang::TType componentType(glslangType.getBasicType());
8413 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008414 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008415 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8416 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008417 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008418 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008419 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8420 bool zero = nextConst >= consts.size();
8421 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008422 case glslang::EbtInt:
8423 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8424 break;
8425 case glslang::EbtUint:
8426 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8427 break;
8428 case glslang::EbtFloat:
8429 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8430 break;
8431 case glslang::EbtBool:
8432 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8433 break;
8434#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008435 case glslang::EbtInt8:
8436 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8437 break;
8438 case glslang::EbtUint8:
8439 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8440 break;
8441 case glslang::EbtInt16:
8442 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8443 break;
8444 case glslang::EbtUint16:
8445 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8446 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008447 case glslang::EbtInt64:
8448 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8449 break;
8450 case glslang::EbtUint64:
8451 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008453 case glslang::EbtDouble:
8454 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8455 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008456 case glslang::EbtFloat16:
8457 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8458 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008459#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008460 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008461 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008462 break;
8463 }
8464 ++nextConst;
8465 }
8466 } else {
8467 // we have a non-aggregate (scalar) constant
8468 bool zero = nextConst >= consts.size();
8469 spv::Id scalar = 0;
8470 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008471 case glslang::EbtInt:
8472 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8473 break;
8474 case glslang::EbtUint:
8475 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8476 break;
8477 case glslang::EbtFloat:
8478 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8479 break;
8480 case glslang::EbtBool:
8481 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8482 break;
8483#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008484 case glslang::EbtInt8:
8485 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8486 break;
8487 case glslang::EbtUint8:
8488 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8489 break;
8490 case glslang::EbtInt16:
8491 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8492 break;
8493 case glslang::EbtUint16:
8494 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8495 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008496 case glslang::EbtInt64:
8497 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8498 break;
8499 case glslang::EbtUint64:
8500 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8501 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008502 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008503 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008504 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008505 case glslang::EbtFloat16:
8506 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8507 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008508 case glslang::EbtReference:
8509 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8510 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8511 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008512#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008513 case glslang::EbtString:
8514 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8515 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008516 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008517 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008518 break;
8519 }
8520 ++nextConst;
8521 return scalar;
8522 }
8523
8524 return builder.makeCompositeConstant(typeId, spvConsts);
8525}
8526
John Kessenich7c1aa102015-10-15 13:29:11 -06008527// Return true if the node is a constant or symbol whose reading has no
8528// non-trivial observable cost or effect.
8529bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8530{
8531 // don't know what this is
8532 if (node == nullptr)
8533 return false;
8534
8535 // a constant is safe
8536 if (node->getAsConstantUnion() != nullptr)
8537 return true;
8538
8539 // not a symbol means non-trivial
8540 if (node->getAsSymbolNode() == nullptr)
8541 return false;
8542
8543 // a symbol, depends on what's being read
8544 switch (node->getType().getQualifier().storage) {
8545 case glslang::EvqTemporary:
8546 case glslang::EvqGlobal:
8547 case glslang::EvqIn:
8548 case glslang::EvqInOut:
8549 case glslang::EvqConst:
8550 case glslang::EvqConstReadOnly:
8551 case glslang::EvqUniform:
8552 return true;
8553 default:
8554 return false;
8555 }
qining25262b32016-05-06 17:25:16 -04008556}
John Kessenich7c1aa102015-10-15 13:29:11 -06008557
8558// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008559// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008560// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008561// Return true if trivial.
8562bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8563{
8564 if (node == nullptr)
8565 return false;
8566
John Kessenich84cc15f2017-05-24 16:44:47 -06008567 // count non scalars as trivial, as well as anything coming from HLSL
8568 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008569 return true;
8570
John Kessenich7c1aa102015-10-15 13:29:11 -06008571 // symbols and constants are trivial
8572 if (isTrivialLeaf(node))
8573 return true;
8574
8575 // otherwise, it needs to be a simple operation or one or two leaf nodes
8576
8577 // not a simple operation
8578 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8579 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8580 if (binaryNode == nullptr && unaryNode == nullptr)
8581 return false;
8582
8583 // not on leaf nodes
8584 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8585 return false;
8586
8587 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8588 return false;
8589 }
8590
8591 switch (node->getAsOperator()->getOp()) {
8592 case glslang::EOpLogicalNot:
8593 case glslang::EOpConvIntToBool:
8594 case glslang::EOpConvUintToBool:
8595 case glslang::EOpConvFloatToBool:
8596 case glslang::EOpConvDoubleToBool:
8597 case glslang::EOpEqual:
8598 case glslang::EOpNotEqual:
8599 case glslang::EOpLessThan:
8600 case glslang::EOpGreaterThan:
8601 case glslang::EOpLessThanEqual:
8602 case glslang::EOpGreaterThanEqual:
8603 case glslang::EOpIndexDirect:
8604 case glslang::EOpIndexDirectStruct:
8605 case glslang::EOpLogicalXor:
8606 case glslang::EOpAny:
8607 case glslang::EOpAll:
8608 return true;
8609 default:
8610 return false;
8611 }
8612}
8613
8614// Emit short-circuiting code, where 'right' is never evaluated unless
8615// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008616spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8617 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008618{
8619 spv::Id boolTypeId = builder.makeBoolType();
8620
8621 // emit left operand
8622 builder.clearAccessChain();
8623 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008624 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008625
8626 // Operands to accumulate OpPhi operands
8627 std::vector<spv::Id> phiOperands;
8628 // accumulate left operand's phi information
8629 phiOperands.push_back(leftId);
8630 phiOperands.push_back(builder.getBuildPoint()->getId());
8631
8632 // Make the two kinds of operation symmetric with a "!"
8633 // || => emit "if (! left) result = right"
8634 // && => emit "if ( left) result = right"
8635 //
8636 // TODO: this runtime "not" for || could be avoided by adding functionality
8637 // to 'builder' to have an "else" without an "then"
8638 if (op == glslang::EOpLogicalOr)
8639 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8640
8641 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008642 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008643
8644 // emit right operand as the "then" part of the "if"
8645 builder.clearAccessChain();
8646 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008647 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008648
8649 // accumulate left operand's phi information
8650 phiOperands.push_back(rightId);
8651 phiOperands.push_back(builder.getBuildPoint()->getId());
8652
8653 // finish the "if"
8654 ifBuilder.makeEndIf();
8655
8656 // phi together the two results
8657 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8658}
8659
John Kessenicha28f7a72019-08-06 07:00:58 -06008660#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008661// Return type Id of the imported set of extended instructions corresponds to the name.
8662// Import this set if it has not been imported yet.
8663spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8664{
8665 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8666 return extBuiltinMap[name];
8667 else {
Rex Xu51596642016-09-21 18:56:12 +08008668 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008669 spv::Id extBuiltins = builder.import(name);
8670 extBuiltinMap[name] = extBuiltins;
8671 return extBuiltins;
8672 }
8673}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008674#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008675
John Kessenich140f3df2015-06-26 16:58:36 -06008676}; // end anonymous namespace
8677
8678namespace glslang {
8679
John Kessenich68d78fd2015-07-12 19:28:10 -06008680void GetSpirvVersion(std::string& version)
8681{
John Kessenich9e55f632015-07-15 10:03:39 -06008682 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008683 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008684 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008685 version = buf;
8686}
8687
John Kessenicha372a3e2017-11-02 22:32:14 -06008688// For low-order part of the generator's magic number. Bump up
8689// when there is a change in the style (e.g., if SSA form changes,
8690// or a different instruction sequence to do something gets used).
8691int GetSpirvGeneratorVersion()
8692{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008693 // return 1; // start
8694 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008695 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008696 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008697 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008698 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8699 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008700 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008701 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008702 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8703 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008704}
8705
John Kessenich140f3df2015-06-26 16:58:36 -06008706// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008707void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008708{
8709 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008710 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008711 if (out.fail())
8712 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008713 for (int i = 0; i < (int)spirv.size(); ++i) {
8714 unsigned int word = spirv[i];
8715 out.write((const char*)&word, 4);
8716 }
8717 out.close();
8718}
8719
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008720// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008721void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008722{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008723#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008724 std::ofstream out;
8725 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008726 if (out.fail())
8727 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008728 out << "\t// " <<
8729 GetSpirvGeneratorVersion() <<
8730 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8731 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008732 if (varName != nullptr) {
8733 out << "\t #pragma once" << std::endl;
8734 out << "const uint32_t " << varName << "[] = {" << std::endl;
8735 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008736 const int WORDS_PER_LINE = 8;
8737 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8738 out << "\t";
8739 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8740 const unsigned int word = spirv[i + j];
8741 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8742 if (i + j + 1 < (int)spirv.size()) {
8743 out << ",";
8744 }
8745 }
8746 out << std::endl;
8747 }
Flavio15017db2017-02-15 14:29:33 -08008748 if (varName != nullptr) {
8749 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008750 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008751 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008752 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008753#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008754}
8755
John Kessenich140f3df2015-06-26 16:58:36 -06008756//
8757// Set up the glslang traversal
8758//
John Kessenich4e11b612018-08-30 16:56:59 -06008759void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008760{
Lei Zhang17535f72016-05-04 15:55:59 -04008761 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008762 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008763}
8764
John Kessenich4e11b612018-08-30 16:56:59 -06008765void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008766 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008767{
John Kessenich140f3df2015-06-26 16:58:36 -06008768 TIntermNode* root = intermediate.getTreeRoot();
8769
8770 if (root == 0)
8771 return;
8772
John Kessenich4e11b612018-08-30 16:56:59 -06008773 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008774 if (options == nullptr)
8775 options = &defaultOptions;
8776
John Kessenich4e11b612018-08-30 16:56:59 -06008777 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008778
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008779 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008780 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008781 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008782 it.dumpSpv(spirv);
8783
GregFfb03a552018-03-29 11:49:14 -06008784#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008785 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8786 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008787 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008788 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8789 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008790 prelegalization = false;
8791 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008792 else if (options->stripDebugInfo) {
8793 // Strip debug info even if optimization is disabled.
8794 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8795 }
John Kessenich717c80a2018-08-23 15:17:10 -06008796
John Kessenich4e11b612018-08-30 16:56:59 -06008797 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008798 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008799
John Kessenich717c80a2018-08-23 15:17:10 -06008800 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008801 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008802
GregFcd1f1692017-09-21 18:40:22 -06008803#endif
8804
John Kessenich4e11b612018-08-30 16:56:59 -06008805 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008806}
8807
8808}; // end namespace glslang