blob: ddc637837d220237c3c44fb05d97c9f615913c41 [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
Tobski8c1a3a02020-11-04 16:24:23 +00001091 case glslang::ElfR64ui:
1092 case glslang::ElfR64i:
1093 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
1094 builder.addCapability(spv::CapabilityInt64ImageEXT);
John Kessenich5d0fa972016-02-15 11:57:00 -07001095 default:
1096 break;
1097 }
1098
1099 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001100 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001101 case glslang::ElfNone: return spv::ImageFormatUnknown;
1102 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1103 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1104 case glslang::ElfR32f: return spv::ImageFormatR32f;
1105 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1106 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1107 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1108 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1109 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1110 case glslang::ElfR16f: return spv::ImageFormatR16f;
1111 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1112 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1113 case glslang::ElfRg16: return spv::ImageFormatRg16;
1114 case glslang::ElfRg8: return spv::ImageFormatRg8;
1115 case glslang::ElfR16: return spv::ImageFormatR16;
1116 case glslang::ElfR8: return spv::ImageFormatR8;
1117 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1118 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1119 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1120 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1121 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1122 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1123 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1124 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1125 case glslang::ElfR32i: return spv::ImageFormatR32i;
1126 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1127 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1128 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1129 case glslang::ElfR16i: return spv::ImageFormatR16i;
1130 case glslang::ElfR8i: return spv::ImageFormatR8i;
1131 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1132 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1133 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1134 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1135 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1136 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1137 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1138 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1139 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1140 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
Tobski8c1a3a02020-11-04 16:24:23 +00001141 case glslang::ElfR64ui: return spv::ImageFormatR64ui;
1142 case glslang::ElfR64i: return spv::ImageFormatR64i;
John Kessenich4016e382016-07-15 11:53:56 -06001143 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001144 }
1145}
1146
John Kessenich8985fc92020-03-03 10:25:07 -07001147spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1148 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001149{
John Kesseniche18fd202018-01-30 11:01:39 -07001150 if (selectionNode.getFlatten())
1151 return spv::SelectionControlFlattenMask;
1152 if (selectionNode.getDontFlatten())
1153 return spv::SelectionControlDontFlattenMask;
1154 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001155}
1156
John Kessenich8985fc92020-03-03 10:25:07 -07001157spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1158 const
steve-lunargf1709e72017-05-02 20:14:50 -06001159{
John Kesseniche18fd202018-01-30 11:01:39 -07001160 if (switchNode.getFlatten())
1161 return spv::SelectionControlFlattenMask;
1162 if (switchNode.getDontFlatten())
1163 return spv::SelectionControlDontFlattenMask;
1164 return spv::SelectionControlMaskNone;
1165}
1166
John Kessenicha2858d92018-01-31 08:11:18 -07001167// return a non-0 dependency if the dependency argument must be set
1168spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001169 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001170{
1171 spv::LoopControlMask control = spv::LoopControlMaskNone;
1172
1173 if (loopNode.getDontUnroll())
1174 control = control | spv::LoopControlDontUnrollMask;
1175 if (loopNode.getUnroll())
1176 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001177 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001178 control = control | spv::LoopControlDependencyInfiniteMask;
1179 else if (loopNode.getLoopDependency() > 0) {
1180 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001181 operands.push_back((unsigned int)loopNode.getLoopDependency());
1182 }
1183 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1184 if (loopNode.getMinIterations() > 0) {
1185 control = control | spv::LoopControlMinIterationsMask;
1186 operands.push_back(loopNode.getMinIterations());
1187 }
1188 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1189 control = control | spv::LoopControlMaxIterationsMask;
1190 operands.push_back(loopNode.getMaxIterations());
1191 }
1192 if (loopNode.getIterationMultiple() > 1) {
1193 control = control | spv::LoopControlIterationMultipleMask;
1194 operands.push_back(loopNode.getIterationMultiple());
1195 }
1196 if (loopNode.getPeelCount() > 0) {
1197 control = control | spv::LoopControlPeelCountMask;
1198 operands.push_back(loopNode.getPeelCount());
1199 }
1200 if (loopNode.getPartialCount() > 0) {
1201 control = control | spv::LoopControlPartialCountMask;
1202 operands.push_back(loopNode.getPartialCount());
1203 }
John Kessenicha2858d92018-01-31 08:11:18 -07001204 }
John Kesseniche18fd202018-01-30 11:01:39 -07001205
1206 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001207}
1208
John Kessenicha5c5fb62017-05-05 05:09:58 -06001209// Translate glslang type to SPIR-V storage class.
1210spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1211{
Torosdagli06c2eee2020-03-19 11:09:57 -04001212 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001213 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001214 if (type.getQualifier().isPipeInput())
1215 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001216 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001217 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001218
1219 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001220 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001221 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001222 return spv::StorageClassAtomicCounter;
1223 if (type.containsOpaque())
1224 return spv::StorageClassUniformConstant;
1225 }
1226
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001227 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001228 type.getQualifier().isShaderRecord()) {
1229 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001230 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001231
John Kessenichbed4e4f2017-09-08 02:38:07 -06001232 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001233 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001234 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001235 }
1236
1237 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001238 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001239 return spv::StorageClassPushConstant;
1240 if (type.getBasicType() == glslang::EbtBlock)
1241 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001242 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001243 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001244
1245 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001246 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1247 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1248 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001249 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001250#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001251 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1252 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1253 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1254 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1255 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001256#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001257 default:
1258 assert(0);
1259 break;
1260 }
1261
1262 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001263}
1264
John Kessenich5611c6d2018-04-05 11:25:02 -06001265// Add capabilities pertaining to how an array is indexed.
1266void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1267 const glslang::TType& indexType)
1268{
John Kessenichb9197c82019-08-11 07:41:45 -06001269#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001270 if (indexType.getQualifier().isNonUniform()) {
1271 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001272 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001273 if (baseType.getBasicType() == glslang::EbtSampler) {
1274 if (baseType.getQualifier().hasAttachment())
1275 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001276 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001277 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001278 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001279 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1280 else if (baseType.isImage())
1281 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1282 else if (baseType.isTexture())
1283 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1284 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1285 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1286 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1287 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1288 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1289 }
1290 } else {
1291 // assume a dynamically uniform index
1292 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001293 if (baseType.getQualifier().hasAttachment()) {
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::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001296 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001297 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001298 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001299 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001300 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001301 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001302 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001303 }
1304 }
John Kessenichb9197c82019-08-11 07:41:45 -06001305#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001306}
1307
qining25262b32016-05-06 17:25:16 -04001308// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001309// descriptor set.
1310bool IsDescriptorResource(const glslang::TType& type)
1311{
John Kessenichf7497e22016-03-08 21:36:22 -07001312 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001313 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001314 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001315 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001316 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001317
1318 // non block...
1319 // basically samplerXXX/subpass/sampler/texture are all included
1320 // if they are the global-scope-class, not the function parameter
1321 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001322 if (type.getBasicType() == glslang::EbtSampler ||
1323 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001324 return type.getQualifier().isUniformOrBuffer();
1325
1326 // None of the above.
1327 return false;
1328}
1329
John Kesseniche0b6cad2015-12-24 10:30:13 -07001330void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1331{
1332 if (child.layoutMatrix == glslang::ElmNone)
1333 child.layoutMatrix = parent.layoutMatrix;
1334
1335 if (parent.invariant)
1336 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001337 if (parent.flat)
1338 child.flat = true;
1339 if (parent.centroid)
1340 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001341#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001342 if (parent.nopersp)
1343 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001344 if (parent.explicitInterp)
1345 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001346 if (parent.perPrimitiveNV)
1347 child.perPrimitiveNV = true;
1348 if (parent.perViewNV)
1349 child.perViewNV = true;
1350 if (parent.perTaskNV)
1351 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001352 if (parent.patch)
1353 child.patch = true;
1354 if (parent.sample)
1355 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001356 if (parent.coherent)
1357 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001358 if (parent.devicecoherent)
1359 child.devicecoherent = true;
1360 if (parent.queuefamilycoherent)
1361 child.queuefamilycoherent = true;
1362 if (parent.workgroupcoherent)
1363 child.workgroupcoherent = true;
1364 if (parent.subgroupcoherent)
1365 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001366 if (parent.shadercallcoherent)
1367 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001368 if (parent.nonprivate)
1369 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001370 if (parent.volatil)
1371 child.volatil = true;
1372 if (parent.restrict)
1373 child.restrict = true;
1374 if (parent.readonly)
1375 child.readonly = true;
1376 if (parent.writeonly)
1377 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001378#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001379}
1380
John Kessenichf2b7f332016-09-01 17:05:23 -06001381bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001382{
John Kessenich7b9fa252016-01-21 18:56:57 -07001383 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001384 // - struct members might inherit from a struct declaration
1385 // (note that non-block structs don't explicitly inherit,
1386 // only implicitly, meaning no decoration involved)
1387 // - affect decorations on the struct members
1388 // (note smooth does not, and expecting something like volatile
1389 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001390 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001391 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001392}
1393
John Kessenich140f3df2015-06-26 16:58:36 -06001394//
1395// Implement the TGlslangToSpvTraverser class.
1396//
1397
John Kessenich8985fc92020-03-03 10:25:07 -07001398TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1399 const glslang::TIntermediate* glslangIntermediate,
1400 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1401 TIntermTraverser(true, false, true),
1402 options(options),
1403 shaderEntry(nullptr), currentFunction(nullptr),
1404 sequenceDepth(0), logger(buildLogger),
1405 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1406 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1407 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001408 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1409 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001410{
1411 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1412
1413 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001414 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1415 glslangIntermediate->getVersion());
1416
John Kessenich121853f2017-05-31 17:11:16 -06001417 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001418 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001419 builder.setSourceFile(glslangIntermediate->getSourceFile());
1420
1421 // Set the source shader's text. If for SPV version 1.0, include
1422 // a preamble in comments stating the OpModuleProcessed instructions.
1423 // Otherwise, emit those as actual instructions.
1424 std::string text;
1425 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1426 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001427 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001428 text.append("// OpModuleProcessed ");
1429 text.append(processes[p]);
1430 text.append("\n");
1431 } else
1432 builder.addModuleProcessed(processes[p]);
1433 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001434 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001435 text.append("#line 1\n");
1436 text.append(glslangIntermediate->getSourceText());
1437 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001438 // Pass name and text for all included files
1439 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1440 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1441 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001442 }
John Kessenich140f3df2015-06-26 16:58:36 -06001443 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001444
1445 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1446 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1447
1448 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1449 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001450 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001451 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001452 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001453 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001454 memoryModel = spv::MemoryModelVulkanKHR;
1455 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001456 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001457 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001458 builder.setMemoryModel(addressingModel, memoryModel);
1459
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001460 if (glslangIntermediate->usingVariablePointers()) {
1461 builder.addCapability(spv::CapabilityVariablePointers);
1462 }
1463
John Kessenicheee9d532016-09-19 18:09:30 -06001464 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1465 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001466
1467 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001468 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1469 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001470 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001471
1472 // Add the top-level modes for this shader.
1473
John Kessenich92187592016-02-01 13:45:25 -07001474 if (glslangIntermediate->getXfbMode()) {
1475 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001476 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001477 }
John Kessenich140f3df2015-06-26 16:58:36 -06001478
alelenv59216d52020-05-21 04:38:41 -07001479 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001480 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1481 }
1482
John Kessenich140f3df2015-06-26 16:58:36 -06001483 unsigned int mode;
1484 switch (glslangIntermediate->getStage()) {
1485 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001486 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001487 break;
1488
John Kessenicha28f7a72019-08-06 07:00:58 -06001489 case EShLangFragment:
1490 builder.addCapability(spv::CapabilityShader);
1491 if (glslangIntermediate->getPixelCenterInteger())
1492 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1493
1494 if (glslangIntermediate->getOriginUpperLeft())
1495 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1496 else
1497 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1498
1499 if (glslangIntermediate->getEarlyFragmentTests())
1500 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1501
1502 if (glslangIntermediate->getPostDepthCoverage()) {
1503 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1504 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1505 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1506 }
1507
John Kessenichb9197c82019-08-11 07:41:45 -06001508 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1509 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1510
1511#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001512
John Kessenicha28f7a72019-08-06 07:00:58 -06001513 switch(glslangIntermediate->getDepth()) {
1514 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1515 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1516 default: mode = spv::ExecutionModeMax; break;
1517 }
1518 if (mode != spv::ExecutionModeMax)
1519 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001520 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001521 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1522 break;
1523 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1524 break;
1525 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1526 break;
1527 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1528 break;
1529 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1530 break;
1531 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1532 break;
1533 default: mode = spv::ExecutionModeMax;
1534 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001535 }
1536 if (mode != spv::ExecutionModeMax) {
1537 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1538 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1539 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1540 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1541 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1542 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1543 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1544 } else {
1545 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1546 }
1547 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1548 }
John Kessenichb9197c82019-08-11 07:41:45 -06001549#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001550 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001551
John Kessenicha28f7a72019-08-06 07:00:58 -06001552 case EShLangCompute:
1553 builder.addCapability(spv::CapabilityShader);
1554 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1555 glslangIntermediate->getLocalSize(1),
1556 glslangIntermediate->getLocalSize(2));
1557 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1558 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1559 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1560 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1561 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1562 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1563 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1564 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1565 }
1566 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001567#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001568 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001569 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001570 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001571
steve-lunarge7412492017-03-23 11:56:07 -06001572 glslang::TLayoutGeometry primitive;
1573
1574 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001575 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1576 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001577 primitive = glslangIntermediate->getOutputPrimitive();
1578 } else {
1579 primitive = glslangIntermediate->getInputPrimitive();
1580 }
1581
1582 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001583 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1584 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1585 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001586 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001587 }
John Kessenich4016e382016-07-15 11:53:56 -06001588 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001589 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1590
John Kesseniche6903322015-10-13 16:29:02 -06001591 switch (glslangIntermediate->getVertexSpacing()) {
1592 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1593 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1594 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001595 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001596 }
John Kessenich4016e382016-07-15 11:53:56 -06001597 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001598 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1599
1600 switch (glslangIntermediate->getVertexOrder()) {
1601 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1602 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001603 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001604 }
John Kessenich4016e382016-07-15 11:53:56 -06001605 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001606 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1607
1608 if (glslangIntermediate->getPointMode())
1609 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001610 break;
1611
1612 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001613 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001614 switch (glslangIntermediate->getInputPrimitive()) {
1615 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1616 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1617 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001618 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001619 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001620 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001621 }
John Kessenich4016e382016-07-15 11:53:56 -06001622 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001623 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001624
John Kessenich140f3df2015-06-26 16:58:36 -06001625 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1626
1627 switch (glslangIntermediate->getOutputPrimitive()) {
1628 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1629 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1630 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001631 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001632 }
John Kessenich4016e382016-07-15 11:53:56 -06001633 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001634 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1635 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1636 break;
1637
Daniel Kochdb32b242020-03-17 20:42:47 -04001638 case EShLangRayGen:
1639 case EShLangIntersect:
1640 case EShLangAnyHit:
1641 case EShLangClosestHit:
1642 case EShLangMiss:
1643 case EShLangCallable:
1644 {
1645 auto& extensions = glslangIntermediate->getRequestedExtensions();
1646 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1647 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1648 builder.addExtension("SPV_KHR_ray_tracing");
1649 }
1650 else {
1651 builder.addCapability(spv::CapabilityRayTracingNV);
1652 builder.addExtension("SPV_NV_ray_tracing");
1653 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001654 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001655 }
Chao Chen3c366992018-09-19 11:41:59 -07001656 case EShLangTaskNV:
1657 case EShLangMeshNV:
1658 builder.addCapability(spv::CapabilityMeshShadingNV);
1659 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1660 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1661 glslangIntermediate->getLocalSize(1),
1662 glslangIntermediate->getLocalSize(2));
1663 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001664 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1665 glslangIntermediate->getVertices());
1666 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1667 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001668
1669 switch (glslangIntermediate->getOutputPrimitive()) {
1670 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1671 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1672 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1673 default: mode = spv::ExecutionModeMax; break;
1674 }
1675 if (mode != spv::ExecutionModeMax)
1676 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1677 }
1678 break;
1679#endif
1680
John Kessenich140f3df2015-06-26 16:58:36 -06001681 default:
1682 break;
1683 }
John Kessenich140f3df2015-06-26 16:58:36 -06001684}
1685
John Kessenichfca82622016-11-26 13:23:20 -07001686// Finish creating SPV, after the traversal is complete.
1687void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001688{
John Kessenichf04c51b2018-08-03 15:56:12 -06001689 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001690 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001691 builder.setBuildPoint(shaderEntry->getLastBlock());
1692 builder.leaveFunction();
1693 }
1694
John Kessenich7ba63412015-12-20 17:37:07 -07001695 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001696 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1697 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001698
David Neto8c3d5b42019-10-21 14:50:31 -04001699 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001700 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001701 // Note: WebGPU code generation must have the opportunity to aggressively
1702 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001703 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001704}
1705
John Kessenichfca82622016-11-26 13:23:20 -07001706// Write the SPV into 'out'.
1707void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001708{
John Kessenichfca82622016-11-26 13:23:20 -07001709 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001710}
1711
1712//
1713// Implement the traversal functions.
1714//
1715// Return true from interior nodes to have the external traversal
1716// continue on to children. Return false if children were
1717// already processed.
1718//
1719
1720//
qining25262b32016-05-06 17:25:16 -04001721// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001722// - uniform/input reads
1723// - output writes
1724// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1725// - something simple that degenerates into the last bullet
1726//
1727void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1728{
qining75d1d802016-04-06 14:42:01 -04001729 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001730 if (symbol->getType().isStruct())
1731 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1732
qining75d1d802016-04-06 14:42:01 -04001733 if (symbol->getType().getQualifier().isSpecConstant())
1734 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1735
Rex Xuf6e0fe82020-10-23 22:54:35 +08001736#ifdef ENABLE_HLSL
1737 // Skip symbol handling if it is string-typed
1738 if (symbol->getBasicType() == glslang::EbtString)
1739 return;
1740#endif
1741
John Kessenich140f3df2015-06-26 16:58:36 -06001742 // getSymbolId() will set up all the IO decorations on the first call.
1743 // Formal function parameters were mapped during makeFunctions().
1744 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001745
John Kessenich7ba63412015-12-20 17:37:07 -07001746 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001747 if (!symbol->getType().getQualifier().isParamInput() &&
1748 !symbol->getType().getQualifier().isParamOutput()) {
1749 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1750 // Consider adding to the OpEntryPoint interface list.
1751 // Only looking at structures if they have at least one member.
1752 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1753 spv::StorageClass sc = builder.getStorageClass(id);
1754 // Before SPIR-V 1.4, we only want to include Input and Output.
1755 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001756 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001757 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1758 iOSet.insert(id);
1759 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001760 }
John Kessenich5f77d862017-09-19 11:09:59 -06001761 }
John Kessenich9c14f772019-06-17 08:38:35 -06001762
Daniel Kochdb32b242020-03-17 20:42:47 -04001763 // If the SPIR-V type is required to be different than the AST type
1764 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001765 // translate now from the SPIR-V type to the AST type, for the consuming
1766 // operation.
1767 // Note this turns it from an l-value to an r-value.
1768 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1769 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1770 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001771 }
1772
1773 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001774 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001775 // Prepare to generate code for the access
1776
1777 // L-value chains will be computed left to right. We're on the symbol now,
1778 // which is the left-most part of the access chain, so now is "clear" time,
1779 // followed by setting the base.
1780 builder.clearAccessChain();
1781
1782 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001783 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001784 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001785 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001786 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001787 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001788 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001789 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001790 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1791 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001792 builder.setAccessChainRValue(id);
1793 else
1794 builder.setAccessChainLValue(id);
1795 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001796
John Kessenichb9197c82019-08-11 07:41:45 -06001797#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001798 // Process linkage-only nodes for any special additional interface work.
1799 if (linkageOnly) {
1800 if (glslangIntermediate->getHlslFunctionality1()) {
1801 // Map implicit counter buffers to their originating buffers, which should have been
1802 // seen by now, given earlier pruning of unused counters, and preservation of order
1803 // of declaration.
1804 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1805 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1806 // Save possible originating buffers for counter buffers, keyed by
1807 // making the potential counter-buffer name.
1808 std::string keyName = symbol->getName().c_str();
1809 keyName = glslangIntermediate->addCounterBufferName(keyName);
1810 counterOriginator[keyName] = symbol;
1811 } else {
1812 // Handle a counter buffer, by finding the saved originating buffer.
1813 std::string keyName = symbol->getName().c_str();
1814 auto it = counterOriginator.find(keyName);
1815 if (it != counterOriginator.end()) {
1816 id = getSymbolId(it->second);
1817 if (id != spv::NoResult) {
1818 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001819 if (counterId != spv::NoResult) {
1820 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001821 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001822 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001823 }
1824 }
1825 }
1826 }
1827 }
1828 }
John Kessenich155d3512019-08-08 23:29:20 -06001829#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001830}
1831
1832bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1833{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001834 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001835 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1836 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1837 }
1838 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1839 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1840 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001841
qining40887662016-04-03 22:20:42 -04001842 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1843 if (node->getType().getQualifier().isSpecConstant())
1844 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1845
John Kessenich140f3df2015-06-26 16:58:36 -06001846 // First, handle special cases
1847 switch (node->getOp()) {
1848 case glslang::EOpAssign:
1849 case glslang::EOpAddAssign:
1850 case glslang::EOpSubAssign:
1851 case glslang::EOpMulAssign:
1852 case glslang::EOpVectorTimesMatrixAssign:
1853 case glslang::EOpVectorTimesScalarAssign:
1854 case glslang::EOpMatrixTimesScalarAssign:
1855 case glslang::EOpMatrixTimesMatrixAssign:
1856 case glslang::EOpDivAssign:
1857 case glslang::EOpModAssign:
1858 case glslang::EOpAndAssign:
1859 case glslang::EOpInclusiveOrAssign:
1860 case glslang::EOpExclusiveOrAssign:
1861 case glslang::EOpLeftShiftAssign:
1862 case glslang::EOpRightShiftAssign:
1863 // A bin-op assign "a += b" means the same thing as "a = a + b"
1864 // where a is evaluated before b. For a simple assignment, GLSL
1865 // says to evaluate the left before the right. So, always, left
1866 // node then right node.
1867 {
1868 // get the left l-value, save it away
1869 builder.clearAccessChain();
1870 node->getLeft()->traverse(this);
1871 spv::Builder::AccessChain lValue = builder.getAccessChain();
1872
1873 // evaluate the right
1874 builder.clearAccessChain();
1875 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001876 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001877
1878 if (node->getOp() != glslang::EOpAssign) {
1879 // the left is also an r-value
1880 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001881 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001882
1883 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001884 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001885 TranslateNoContractionDecoration(node->getType().getQualifier()),
1886 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001887 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001888 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1889 node->getType().getBasicType());
1890
1891 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001892 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001893 }
1894
1895 // store the result
1896 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001897 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001898
1899 // assignments are expressions having an rValue after they are evaluated...
1900 builder.clearAccessChain();
1901 builder.setAccessChainRValue(rValue);
1902 }
1903 return false;
1904 case glslang::EOpIndexDirect:
1905 case glslang::EOpIndexDirectStruct:
1906 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001907 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001908 // Get the left part of the access chain.
1909 node->getLeft()->traverse(this);
1910
1911 // Add the next element in the chain
1912
David Netoa901ffe2016-06-08 14:11:40 +01001913 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001914 if (! node->getLeft()->getType().isArray() &&
1915 node->getLeft()->getType().isVector() &&
1916 node->getOp() == glslang::EOpIndexDirect) {
1917 // This is essentially a hard-coded vector swizzle of size 1,
1918 // so short circuit the access-chain stuff with a swizzle.
1919 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001920 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001921 int dummySize;
1922 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1923 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001924 glslangIntermediate->getBaseAlignmentScalar(
1925 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001926 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001927
1928 // Load through a block reference is performed with a dot operator that
1929 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1930 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001931 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001932 !node->getLeft()->getType().isArray() &&
1933 node->getOp() == glslang::EOpIndexDirectStruct)
1934 {
1935 spv::Id left = accessChainLoad(node->getLeft()->getType());
1936 builder.clearAccessChain();
1937 builder.setAccessChainLValue(left);
1938 }
1939
David Netoa901ffe2016-06-08 14:11:40 +01001940 int spvIndex = glslangIndex;
1941 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1942 node->getOp() == glslang::EOpIndexDirectStruct)
1943 {
1944 // This may be, e.g., an anonymous block-member selection, which generally need
1945 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001946 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1947 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1948 std::vector<int>& remapper = memberRemapper[glslangId];
1949 assert(remapper.size() > 0);
1950 spvIndex = remapper[glslangIndex];
1951 }
David Netoa901ffe2016-06-08 14:11:40 +01001952 }
John Kessenichebb50532016-05-16 19:22:05 -06001953
David Netoa901ffe2016-06-08 14:11:40 +01001954 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001955 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1956 TranslateCoherent(node->getLeft()->getType()),
1957 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001958
1959 // Add capabilities here for accessing PointSize and clip/cull distance.
1960 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001961 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001962 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001963 }
1964 }
1965 return false;
1966 case glslang::EOpIndexIndirect:
1967 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001968 // Array, matrix, or vector indirection with variable index.
1969 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001970 // matrices are arrays of vectors, so will also work for a matrix.
1971 // Will use the access chain's 'component' for variable index into a vector.
1972
1973 // This adapter is building access chains left to right.
1974 // Set up the access chain to the left.
1975 node->getLeft()->traverse(this);
1976
1977 // save it so that computing the right side doesn't trash it
1978 spv::Builder::AccessChain partial = builder.getAccessChain();
1979
1980 // compute the next index in the chain
1981 builder.clearAccessChain();
1982 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001983 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001984
John Kessenich5611c6d2018-04-05 11:25:02 -06001985 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1986
John Kessenich140f3df2015-06-26 16:58:36 -06001987 // restore the saved access chain
1988 builder.setAccessChain(partial);
1989
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001990 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1991 int dummySize;
1992 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1993 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001994 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1995 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001996 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001997 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1998 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001999 }
2000 return false;
2001 case glslang::EOpVectorSwizzle:
2002 {
2003 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002004 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06002005 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002006 int dummySize;
2007 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
2008 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07002009 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2010 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06002011 }
2012 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07002013 case glslang::EOpMatrixSwizzle:
2014 logger->missingFunctionality("matrix swizzle");
2015 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06002016 case glslang::EOpLogicalOr:
2017 case glslang::EOpLogicalAnd:
2018 {
2019
2020 // These may require short circuiting, but can sometimes be done as straight
2021 // binary operations. The right operand must be short circuited if it has
2022 // side effects, and should probably be if it is complex.
2023 if (isTrivial(node->getRight()->getAsTyped()))
2024 break; // handle below as a normal binary operation
2025 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07002026 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
2027 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06002028 builder.clearAccessChain();
2029 builder.setAccessChainRValue(result);
2030 }
2031 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002032 default:
2033 break;
2034 }
2035
2036 // Assume generic binary op...
2037
John Kessenich32cfd492016-02-02 12:37:46 -07002038 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002039 builder.clearAccessChain();
2040 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002041 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002042
John Kessenich32cfd492016-02-02 12:37:46 -07002043 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002044 builder.clearAccessChain();
2045 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002046 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002047
John Kessenich32cfd492016-02-02 12:37:46 -07002048 // get result
John Kessenichead86222018-03-28 18:01:20 -06002049 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002050 TranslateNoContractionDecoration(node->getType().getQualifier()),
2051 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002052 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002053 convertGlslangToSpvType(node->getType()), left, right,
2054 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002055
John Kessenich50e57562015-12-21 21:21:11 -07002056 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002057 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002058 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002059 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002060 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002061 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002062 return false;
2063 }
John Kessenich140f3df2015-06-26 16:58:36 -06002064}
2065
John Kessenich9c14f772019-06-17 08:38:35 -06002066// Figure out what, if any, type changes are needed when accessing a specific built-in.
2067// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2068// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002069std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002070 const glslang::TType& glslangType)
2071{
Daniel Kochdb32b242020-03-17 20:42:47 -04002072 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002073 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002074 case glslang::EbvSubGroupEqMask:
2075 case glslang::EbvSubGroupGeMask:
2076 case glslang::EbvSubGroupGtMask:
2077 case glslang::EbvSubGroupLeMask:
2078 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002079 // these require changing a 64-bit scaler -> a vector of 32-bit components
2080 if (glslangType.isVector())
2081 break;
2082 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2083 builder.makeUintType(64));
2084 return ret;
2085 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002086 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2087 // builtins. During visitBinary we insert a transpose
2088 case glslang::EbvWorldToObject3x4:
2089 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002090 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2091 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2092 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002093 return ret;
2094 }
John Kessenich9c14f772019-06-17 08:38:35 -06002095 default:
2096 break;
2097 }
2098
2099 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2100 return ret;
2101}
2102
2103// For an object previously identified (see getForcedType() and forceType)
2104// as needing type translations, do the translation needed for a load, turning
2105// an L-value into in R-value.
2106spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2107{
2108 const auto forceIt = forceType.find(object);
2109 if (forceIt == forceType.end())
2110 return object;
2111
2112 spv::Id desiredTypeId = forceIt->second;
2113 spv::Id objectTypeId = builder.getTypeId(object);
2114 assert(builder.isPointerType(objectTypeId));
2115 objectTypeId = builder.getContainedTypeId(objectTypeId);
2116 if (builder.isVectorType(objectTypeId) &&
2117 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2118 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2119 // handle 32-bit v.xy* -> 64-bit
2120 builder.clearAccessChain();
2121 builder.setAccessChainLValue(object);
2122 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2123 std::vector<spv::Id> components;
2124 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2125 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2126
2127 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2128 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2129 builder.createCompositeConstruct(vecType, components));
2130 } else {
2131 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2132 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002133 } else if (builder.isMatrixType(objectTypeId)) {
2134 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2135 // and we insert a transpose after loading the original non-transposed builtins
2136 builder.clearAccessChain();
2137 builder.setAccessChainLValue(object);
2138 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2139 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2140
2141 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002142 logger->missingFunctionality("forcing non 32-bit vector type");
2143 }
2144
2145 return object;
2146}
2147
John Kessenich140f3df2015-06-26 16:58:36 -06002148bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2149{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002150 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002151
qining40887662016-04-03 22:20:42 -04002152 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2153 if (node->getType().getQualifier().isSpecConstant())
2154 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2155
John Kessenichfc51d282015-08-19 13:34:18 -06002156 spv::Id result = spv::NoResult;
2157
2158 // try texturing first
2159 result = createImageTextureFunctionCall(node);
2160 if (result != spv::NoResult) {
2161 builder.clearAccessChain();
2162 builder.setAccessChainRValue(result);
2163
2164 return false; // done with this node
2165 }
2166
2167 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002168
2169 if (node->getOp() == glslang::EOpArrayLength) {
2170 // Quite special; won't want to evaluate the operand.
2171
John Kessenich5611c6d2018-04-05 11:25:02 -06002172 // Currently, the front-end does not allow .length() on an array until it is sized,
2173 // except for the last block membeor of an SSBO.
2174 // TODO: If this changes, link-time sized arrays might show up here, and need their
2175 // size extracted.
2176
John Kessenichc9a80832015-09-12 12:17:44 -06002177 // Normal .length() would have been constant folded by the front-end.
2178 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002179 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002180
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002181 spv::Id length;
2182 if (node->getOperand()->getType().isCoopMat()) {
2183 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2184
2185 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2186 assert(builder.isCooperativeMatrixType(typeId));
2187
2188 length = builder.createCooperativeMatrixLength(typeId);
2189 } else {
2190 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2191 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002192 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2193 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002194 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2195 }
John Kessenichc9a80832015-09-12 12:17:44 -06002196
John Kessenich8c869672018-11-28 07:01:37 -07002197 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2198 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2199 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002200 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2201 if (builder.isInSpecConstCodeGenMode()) {
2202 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2203 } else {
2204 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2205 }
2206 }
John Kessenich8c869672018-11-28 07:01:37 -07002207
John Kessenichc9a80832015-09-12 12:17:44 -06002208 builder.clearAccessChain();
2209 builder.setAccessChainRValue(length);
2210
2211 return false;
2212 }
2213
John Kessenichfc51d282015-08-19 13:34:18 -06002214 // Start by evaluating the operand
2215
John Kessenich8c8505c2016-07-26 12:50:38 -06002216 // Does it need a swizzle inversion? If so, evaluation is inverted;
2217 // operate first on the swizzle base, then apply the swizzle.
2218 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002219 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2220 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002221 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2222 invertedType = getInvertedSwizzleType(*node->getOperand());
2223
John Kessenich140f3df2015-06-26 16:58:36 -06002224 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002225 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002226 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002227 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002228 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002229 operandNode = node->getOperand();
2230
2231 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002232
Rex Xufc618912015-09-09 16:42:49 +08002233 spv::Id operand = spv::NoResult;
2234
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002235 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2236
John Kessenichfb4f2332019-08-09 03:49:15 -06002237#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002238 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2239 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002240 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002241 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2242 node->getOp() == glslang::EOpRayQueryProceed ||
2243 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2244 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2245 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2246 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2247 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2248 node->getOp() == glslang::EOpRayQueryTerminate ||
2249 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002250 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002251 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2252 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2253 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002254#endif
2255 {
John Kessenich32cfd492016-02-02 12:37:46 -07002256 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002257 }
John Kessenich140f3df2015-06-26 16:58:36 -06002258
John Kessenichead86222018-03-28 18:01:20 -06002259 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002260 TranslateNoContractionDecoration(node->getType().getQualifier()),
2261 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002262
2263 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002264 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002265 result = createConversion(node->getOp(), decorations, resultType(), operand,
2266 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002267
2268 // if not, then possibly an operation
2269 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002270 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2271 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002272
2273 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002274 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002275 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002276 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002277 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002278
John Kessenich140f3df2015-06-26 16:58:36 -06002279 builder.clearAccessChain();
2280 builder.setAccessChainRValue(result);
2281
2282 return false; // done with this node
2283 }
2284
2285 // it must be a special case, check...
2286 switch (node->getOp()) {
2287 case glslang::EOpPostIncrement:
2288 case glslang::EOpPostDecrement:
2289 case glslang::EOpPreIncrement:
2290 case glslang::EOpPreDecrement:
2291 {
2292 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002293 spv::Id one = 0;
2294 if (node->getBasicType() == glslang::EbtFloat)
2295 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002296#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002297 else if (node->getBasicType() == glslang::EbtDouble)
2298 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002299 else if (node->getBasicType() == glslang::EbtFloat16)
2300 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002301 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2302 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002303 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2304 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002305 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2306 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002307#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002308 else
2309 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002310 glslang::TOperator op;
2311 if (node->getOp() == glslang::EOpPreIncrement ||
2312 node->getOp() == glslang::EOpPostIncrement)
2313 op = glslang::EOpAdd;
2314 else
2315 op = glslang::EOpSub;
2316
John Kessenichead86222018-03-28 18:01:20 -06002317 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002318 convertGlslangToSpvType(node->getType()), operand, one,
2319 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002320 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002321
2322 // The result of operation is always stored, but conditionally the
2323 // consumed result. The consumed result is always an r-value.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002324 builder.accessChainStore(result,
2325 TranslateNonUniformDecoration(node->getOperand()->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06002326 builder.clearAccessChain();
2327 if (node->getOp() == glslang::EOpPreIncrement ||
2328 node->getOp() == glslang::EOpPreDecrement)
2329 builder.setAccessChainRValue(result);
2330 else
2331 builder.setAccessChainRValue(operand);
2332 }
2333
2334 return false;
2335
John Kessenich155d3512019-08-08 23:29:20 -06002336#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002337 case glslang::EOpEmitStreamVertex:
2338 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2339 return false;
2340 case glslang::EOpEndStreamPrimitive:
2341 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2342 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002343 case glslang::EOpRayQueryTerminate:
2344 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2345 return false;
2346 case glslang::EOpRayQueryConfirmIntersection:
2347 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2348 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002349#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002350
2351 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002352 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002353 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002354 }
John Kessenich140f3df2015-06-26 16:58:36 -06002355}
2356
Jeff Bolz53134492019-06-25 13:31:10 -05002357// Construct a composite object, recursively copying members if their types don't match
2358spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2359{
2360 for (int c = 0; c < (int)constituents.size(); ++c) {
2361 spv::Id& constituent = constituents[c];
2362 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2363 spv::Id rType = builder.getTypeId(constituent);
2364 if (lType != rType) {
2365 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2366 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2367 } else if (builder.isStructType(rType)) {
2368 std::vector<spv::Id> rTypeConstituents;
2369 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2370 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002371 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2372 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002373 }
2374 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2375 } else {
2376 assert(builder.isArrayType(rType));
2377 std::vector<spv::Id> rTypeConstituents;
2378 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2379
2380 spv::Id elementRType = builder.getContainedTypeId(rType);
2381 for (int i = 0; i < numrTypeConstituents; ++i) {
2382 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2383 }
2384 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2385 }
2386 }
2387 }
2388 return builder.createCompositeConstruct(resultTypeId, constituents);
2389}
2390
John Kessenich140f3df2015-06-26 16:58:36 -06002391bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2392{
qining27e04a02016-04-14 16:40:20 -04002393 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2394 if (node->getType().getQualifier().isSpecConstant())
2395 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2396
John Kessenichfc51d282015-08-19 13:34:18 -06002397 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002398 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2399 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2400 // SPIR-V, for an out parameter
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002401 std::vector<glslang::TQualifier> complexLValueQualifiers;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002402 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002403
John Kessenich8985fc92020-03-03 10:25:07 -07002404 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2405 invertedType :
2406 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002407
2408 // try texturing
2409 result = createImageTextureFunctionCall(node);
2410 if (result != spv::NoResult) {
2411 builder.clearAccessChain();
2412 builder.setAccessChainRValue(result);
2413
2414 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002415 }
2416#ifndef GLSLANG_WEB
2417 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002418 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002419 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002420 // "imageStore" is a special case, which has no result
2421 return false;
2422 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002423#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002424
John Kessenich140f3df2015-06-26 16:58:36 -06002425 glslang::TOperator binOp = glslang::EOpNull;
2426 bool reduceComparison = true;
2427 bool isMatrix = false;
2428 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002429 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002430
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002431 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2432
John Kessenich140f3df2015-06-26 16:58:36 -06002433 assert(node->getOp());
2434
John Kessenichf6640762016-08-01 19:44:00 -06002435 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002436
2437 switch (node->getOp()) {
2438 case glslang::EOpSequence:
2439 {
2440 if (preVisit)
2441 ++sequenceDepth;
2442 else
2443 --sequenceDepth;
2444
2445 if (sequenceDepth == 1) {
2446 // If this is the parent node of all the functions, we want to see them
2447 // early, so all call points have actual SPIR-V functions to reference.
2448 // In all cases, still let the traverser visit the children for us.
2449 makeFunctions(node->getAsAggregate()->getSequence());
2450
John Kessenich6fccb3c2016-09-19 16:01:41 -06002451 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002452 // anything else gets there, so visit out of order, doing them all now.
2453 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2454
John Kessenich6a60c2f2016-12-08 21:01:59 -07002455 // 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 -06002456 // so do them manually.
2457 visitFunctions(node->getAsAggregate()->getSequence());
2458
2459 return false;
2460 }
2461
2462 return true;
2463 }
2464 case glslang::EOpLinkerObjects:
2465 {
2466 if (visit == glslang::EvPreVisit)
2467 linkageOnly = true;
2468 else
2469 linkageOnly = false;
2470
2471 return true;
2472 }
2473 case glslang::EOpComma:
2474 {
2475 // processing from left to right naturally leaves the right-most
2476 // lying around in the access chain
2477 glslang::TIntermSequence& glslangOperands = node->getSequence();
2478 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2479 glslangOperands[i]->traverse(this);
2480
2481 return false;
2482 }
2483 case glslang::EOpFunction:
2484 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002485 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002486 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002487 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002488 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002489 } else {
2490 handleFunctionEntry(node);
2491 }
2492 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002493 if (inEntryPoint)
2494 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002495 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002496 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002497 }
2498
2499 return true;
2500 case glslang::EOpParameters:
2501 // Parameters will have been consumed by EOpFunction processing, but not
2502 // the body, so we still visited the function node's children, making this
2503 // child redundant.
2504 return false;
2505 case glslang::EOpFunctionCall:
2506 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002507 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002508 if (node->isUserDefined())
2509 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002510 if (result) {
2511 builder.clearAccessChain();
2512 builder.setAccessChainRValue(result);
2513 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002514 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002515
2516 return false;
2517 }
2518 case glslang::EOpConstructMat2x2:
2519 case glslang::EOpConstructMat2x3:
2520 case glslang::EOpConstructMat2x4:
2521 case glslang::EOpConstructMat3x2:
2522 case glslang::EOpConstructMat3x3:
2523 case glslang::EOpConstructMat3x4:
2524 case glslang::EOpConstructMat4x2:
2525 case glslang::EOpConstructMat4x3:
2526 case glslang::EOpConstructMat4x4:
2527 case glslang::EOpConstructDMat2x2:
2528 case glslang::EOpConstructDMat2x3:
2529 case glslang::EOpConstructDMat2x4:
2530 case glslang::EOpConstructDMat3x2:
2531 case glslang::EOpConstructDMat3x3:
2532 case glslang::EOpConstructDMat3x4:
2533 case glslang::EOpConstructDMat4x2:
2534 case glslang::EOpConstructDMat4x3:
2535 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002536 case glslang::EOpConstructIMat2x2:
2537 case glslang::EOpConstructIMat2x3:
2538 case glslang::EOpConstructIMat2x4:
2539 case glslang::EOpConstructIMat3x2:
2540 case glslang::EOpConstructIMat3x3:
2541 case glslang::EOpConstructIMat3x4:
2542 case glslang::EOpConstructIMat4x2:
2543 case glslang::EOpConstructIMat4x3:
2544 case glslang::EOpConstructIMat4x4:
2545 case glslang::EOpConstructUMat2x2:
2546 case glslang::EOpConstructUMat2x3:
2547 case glslang::EOpConstructUMat2x4:
2548 case glslang::EOpConstructUMat3x2:
2549 case glslang::EOpConstructUMat3x3:
2550 case glslang::EOpConstructUMat3x4:
2551 case glslang::EOpConstructUMat4x2:
2552 case glslang::EOpConstructUMat4x3:
2553 case glslang::EOpConstructUMat4x4:
2554 case glslang::EOpConstructBMat2x2:
2555 case glslang::EOpConstructBMat2x3:
2556 case glslang::EOpConstructBMat2x4:
2557 case glslang::EOpConstructBMat3x2:
2558 case glslang::EOpConstructBMat3x3:
2559 case glslang::EOpConstructBMat3x4:
2560 case glslang::EOpConstructBMat4x2:
2561 case glslang::EOpConstructBMat4x3:
2562 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002563 case glslang::EOpConstructF16Mat2x2:
2564 case glslang::EOpConstructF16Mat2x3:
2565 case glslang::EOpConstructF16Mat2x4:
2566 case glslang::EOpConstructF16Mat3x2:
2567 case glslang::EOpConstructF16Mat3x3:
2568 case glslang::EOpConstructF16Mat3x4:
2569 case glslang::EOpConstructF16Mat4x2:
2570 case glslang::EOpConstructF16Mat4x3:
2571 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002572 isMatrix = true;
2573 // fall through
2574 case glslang::EOpConstructFloat:
2575 case glslang::EOpConstructVec2:
2576 case glslang::EOpConstructVec3:
2577 case glslang::EOpConstructVec4:
2578 case glslang::EOpConstructDouble:
2579 case glslang::EOpConstructDVec2:
2580 case glslang::EOpConstructDVec3:
2581 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002582 case glslang::EOpConstructFloat16:
2583 case glslang::EOpConstructF16Vec2:
2584 case glslang::EOpConstructF16Vec3:
2585 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002586 case glslang::EOpConstructBool:
2587 case glslang::EOpConstructBVec2:
2588 case glslang::EOpConstructBVec3:
2589 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002590 case glslang::EOpConstructInt8:
2591 case glslang::EOpConstructI8Vec2:
2592 case glslang::EOpConstructI8Vec3:
2593 case glslang::EOpConstructI8Vec4:
2594 case glslang::EOpConstructUint8:
2595 case glslang::EOpConstructU8Vec2:
2596 case glslang::EOpConstructU8Vec3:
2597 case glslang::EOpConstructU8Vec4:
2598 case glslang::EOpConstructInt16:
2599 case glslang::EOpConstructI16Vec2:
2600 case glslang::EOpConstructI16Vec3:
2601 case glslang::EOpConstructI16Vec4:
2602 case glslang::EOpConstructUint16:
2603 case glslang::EOpConstructU16Vec2:
2604 case glslang::EOpConstructU16Vec3:
2605 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002606 case glslang::EOpConstructInt:
2607 case glslang::EOpConstructIVec2:
2608 case glslang::EOpConstructIVec3:
2609 case glslang::EOpConstructIVec4:
2610 case glslang::EOpConstructUint:
2611 case glslang::EOpConstructUVec2:
2612 case glslang::EOpConstructUVec3:
2613 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002614 case glslang::EOpConstructInt64:
2615 case glslang::EOpConstructI64Vec2:
2616 case glslang::EOpConstructI64Vec3:
2617 case glslang::EOpConstructI64Vec4:
2618 case glslang::EOpConstructUint64:
2619 case glslang::EOpConstructU64Vec2:
2620 case glslang::EOpConstructU64Vec3:
2621 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002622 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002623 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002624 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002625 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002626 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002627 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002628 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002629 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002630 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002631 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002632 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002633 else if (node->getOp() == glslang::EOpConstructStruct ||
2634 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2635 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002636 std::vector<spv::Id> constituents;
2637 for (int c = 0; c < (int)arguments.size(); ++c)
2638 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002639 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002640 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002641 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002642 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002643 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002644
Bas Nieuwenhuizenc9ffeec2020-09-03 03:09:39 +02002645 if (node->getType().getQualifier().isNonUniform()) {
2646 builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
2647 }
2648
John Kessenich140f3df2015-06-26 16:58:36 -06002649 builder.clearAccessChain();
2650 builder.setAccessChainRValue(constructed);
2651
2652 return false;
2653 }
2654
2655 // These six are component-wise compares with component-wise results.
2656 // Forward on to createBinaryOperation(), requesting a vector result.
2657 case glslang::EOpLessThan:
2658 case glslang::EOpGreaterThan:
2659 case glslang::EOpLessThanEqual:
2660 case glslang::EOpGreaterThanEqual:
2661 case glslang::EOpVectorEqual:
2662 case glslang::EOpVectorNotEqual:
2663 {
2664 // Map the operation to a binary
2665 binOp = node->getOp();
2666 reduceComparison = false;
2667 switch (node->getOp()) {
2668 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2669 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2670 default: binOp = node->getOp(); break;
2671 }
2672
2673 break;
2674 }
2675 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002676 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002677 binOp = glslang::EOpMul;
2678 break;
2679 case glslang::EOpOuterProduct:
2680 // two vectors multiplied to make a matrix
2681 binOp = glslang::EOpOuterProduct;
2682 break;
2683 case glslang::EOpDot:
2684 {
qining25262b32016-05-06 17:25:16 -04002685 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002686 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002687 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002688 binOp = glslang::EOpMul;
2689 break;
2690 }
2691 case glslang::EOpMod:
2692 // when an aggregate, this is the floating-point mod built-in function,
2693 // which can be emitted by the one in createBinaryOperation()
2694 binOp = glslang::EOpMod;
2695 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002696
John Kessenich140f3df2015-06-26 16:58:36 -06002697 case glslang::EOpEmitVertex:
2698 case glslang::EOpEndPrimitive:
2699 case glslang::EOpBarrier:
2700 case glslang::EOpMemoryBarrier:
2701 case glslang::EOpMemoryBarrierAtomicCounter:
2702 case glslang::EOpMemoryBarrierBuffer:
2703 case glslang::EOpMemoryBarrierImage:
2704 case glslang::EOpMemoryBarrierShared:
2705 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002706 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002707 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002708 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002709 case glslang::EOpWorkgroupMemoryBarrier:
2710 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002711 case glslang::EOpSubgroupBarrier:
2712 case glslang::EOpSubgroupMemoryBarrier:
2713 case glslang::EOpSubgroupMemoryBarrierBuffer:
2714 case glslang::EOpSubgroupMemoryBarrierImage:
2715 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002716 noReturnValue = true;
2717 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2718 break;
2719
John Kessenich426394d2015-07-23 10:22:48 -06002720 case glslang::EOpAtomicAdd:
2721 case glslang::EOpAtomicMin:
2722 case glslang::EOpAtomicMax:
2723 case glslang::EOpAtomicAnd:
2724 case glslang::EOpAtomicOr:
2725 case glslang::EOpAtomicXor:
2726 case glslang::EOpAtomicExchange:
2727 case glslang::EOpAtomicCompSwap:
2728 atomic = true;
2729 break;
2730
John Kesseniche5eee8f2019-10-18 01:03:11 -06002731#ifndef GLSLANG_WEB
2732 case glslang::EOpAtomicStore:
2733 noReturnValue = true;
2734 // fallthrough
2735 case glslang::EOpAtomicLoad:
2736 atomic = true;
2737 break;
2738
John Kessenich0d0c6d32017-07-23 16:08:26 -06002739 case glslang::EOpAtomicCounterAdd:
2740 case glslang::EOpAtomicCounterSubtract:
2741 case glslang::EOpAtomicCounterMin:
2742 case glslang::EOpAtomicCounterMax:
2743 case glslang::EOpAtomicCounterAnd:
2744 case glslang::EOpAtomicCounterOr:
2745 case glslang::EOpAtomicCounterXor:
2746 case glslang::EOpAtomicCounterExchange:
2747 case glslang::EOpAtomicCounterCompSwap:
2748 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2749 builder.addCapability(spv::CapabilityAtomicStorageOps);
2750 atomic = true;
2751 break;
2752
Ian Romanickb3bd4022019-01-21 08:57:25 -08002753 case glslang::EOpAbsDifference:
2754 case glslang::EOpAddSaturate:
2755 case glslang::EOpSubSaturate:
2756 case glslang::EOpAverage:
2757 case glslang::EOpAverageRounded:
2758 case glslang::EOpMul32x16:
2759 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2760 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2761 binOp = node->getOp();
2762 break;
2763
Daniel Kochdb32b242020-03-17 20:42:47 -04002764 case glslang::EOpIgnoreIntersection:
2765 case glslang::EOpTerminateRay:
2766 case glslang::EOpTrace:
2767 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002768 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2769 noReturnValue = true;
2770 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002771 case glslang::EOpRayQueryInitialize:
2772 case glslang::EOpRayQueryTerminate:
2773 case glslang::EOpRayQueryGenerateIntersection:
2774 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002775 builder.addExtension("SPV_KHR_ray_query");
2776 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002777 noReturnValue = true;
2778 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002779 case glslang::EOpRayQueryProceed:
2780 case glslang::EOpRayQueryGetIntersectionType:
2781 case glslang::EOpRayQueryGetRayTMin:
2782 case glslang::EOpRayQueryGetRayFlags:
2783 case glslang::EOpRayQueryGetIntersectionT:
2784 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2785 case glslang::EOpRayQueryGetIntersectionInstanceId:
2786 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2787 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2788 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2789 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2790 case glslang::EOpRayQueryGetIntersectionFrontFace:
2791 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2792 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2793 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2794 case glslang::EOpRayQueryGetWorldRayDirection:
2795 case glslang::EOpRayQueryGetWorldRayOrigin:
2796 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2797 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2798 builder.addExtension("SPV_KHR_ray_query");
2799 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2800 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002801 case glslang::EOpCooperativeMatrixLoad:
2802 case glslang::EOpCooperativeMatrixStore:
2803 noReturnValue = true;
2804 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002805 case glslang::EOpBeginInvocationInterlock:
2806 case glslang::EOpEndInvocationInterlock:
2807 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2808 noReturnValue = true;
2809 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002810#endif
Chao Chen3c366992018-09-19 11:41:59 -07002811
Jeff Bolz04d73732019-05-31 13:06:01 -05002812 case glslang::EOpDebugPrintf:
2813 noReturnValue = true;
2814 break;
2815
John Kessenich140f3df2015-06-26 16:58:36 -06002816 default:
2817 break;
2818 }
2819
2820 //
2821 // See if it maps to a regular operation.
2822 //
John Kessenich140f3df2015-06-26 16:58:36 -06002823 if (binOp != glslang::EOpNull) {
2824 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2825 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2826 assert(left && right);
2827
2828 builder.clearAccessChain();
2829 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002830 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002831
2832 builder.clearAccessChain();
2833 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002834 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002835
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002836 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002837 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002838 TranslateNoContractionDecoration(node->getType().getQualifier()),
2839 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002840 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002841 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002842 left->getType().getBasicType(), reduceComparison);
2843
2844 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002845 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002846 builder.clearAccessChain();
2847 builder.setAccessChainRValue(result);
2848
2849 return false;
2850 }
2851
John Kessenich426394d2015-07-23 10:22:48 -06002852 //
2853 // Create the list of operands.
2854 //
John Kessenich140f3df2015-06-26 16:58:36 -06002855 glslang::TIntermSequence& glslangOperands = node->getSequence();
2856 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002857 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002858 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002859 // special case l-value operands; there are just a few
2860 bool lvalue = false;
2861 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002862 case glslang::EOpModf:
2863 if (arg == 1)
2864 lvalue = true;
2865 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002866
Torosdagli06c2eee2020-03-19 11:09:57 -04002867 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002868 case glslang::EOpRayQueryTerminate:
2869 case glslang::EOpRayQueryConfirmIntersection:
2870 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002871 case glslang::EOpRayQueryGenerateIntersection:
2872 case glslang::EOpRayQueryGetIntersectionType:
2873 case glslang::EOpRayQueryGetIntersectionT:
2874 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2875 case glslang::EOpRayQueryGetIntersectionInstanceId:
2876 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2877 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2878 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2879 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2880 case glslang::EOpRayQueryGetIntersectionFrontFace:
2881 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2882 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2883 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2884 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2885 if (arg == 0)
2886 lvalue = true;
2887 break;
2888
John Kesseniche5eee8f2019-10-18 01:03:11 -06002889 case glslang::EOpAtomicAdd:
2890 case glslang::EOpAtomicMin:
2891 case glslang::EOpAtomicMax:
2892 case glslang::EOpAtomicAnd:
2893 case glslang::EOpAtomicOr:
2894 case glslang::EOpAtomicXor:
2895 case glslang::EOpAtomicExchange:
2896 case glslang::EOpAtomicCompSwap:
2897 if (arg == 0)
2898 lvalue = true;
2899 break;
2900
John Kessenicha28f7a72019-08-06 07:00:58 -06002901#ifndef GLSLANG_WEB
2902 case glslang::EOpFrexp:
2903 if (arg == 1)
2904 lvalue = true;
2905 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002906 case glslang::EOpInterpolateAtSample:
2907 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002908 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002909 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002910 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002911
2912 // Does it need a swizzle inversion? If so, evaluation is inverted;
2913 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002914 // That is, we transform
2915 //
2916 // interpolate(v.zy) -> interpolate(v).zy
2917 //
John Kessenichecba76f2017-01-06 00:34:48 -07002918 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002919 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002920 invertedType = convertGlslangToSpvType(
2921 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002922 }
Rex Xu7a26c172015-12-08 17:12:09 +08002923 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002924 case glslang::EOpAtomicLoad:
2925 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002926 case glslang::EOpAtomicCounterAdd:
2927 case glslang::EOpAtomicCounterSubtract:
2928 case glslang::EOpAtomicCounterMin:
2929 case glslang::EOpAtomicCounterMax:
2930 case glslang::EOpAtomicCounterAnd:
2931 case glslang::EOpAtomicCounterOr:
2932 case glslang::EOpAtomicCounterXor:
2933 case glslang::EOpAtomicCounterExchange:
2934 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002935 if (arg == 0)
2936 lvalue = true;
2937 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002938 case glslang::EOpAddCarry:
2939 case glslang::EOpSubBorrow:
2940 if (arg == 2)
2941 lvalue = true;
2942 break;
2943 case glslang::EOpUMulExtended:
2944 case glslang::EOpIMulExtended:
2945 if (arg >= 2)
2946 lvalue = true;
2947 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002948 case glslang::EOpCooperativeMatrixLoad:
2949 if (arg == 0 || arg == 1)
2950 lvalue = true;
2951 break;
2952 case glslang::EOpCooperativeMatrixStore:
2953 if (arg == 1)
2954 lvalue = true;
2955 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002956#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002957 default:
2958 break;
2959 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002960 builder.clearAccessChain();
2961 if (invertedType != spv::NoType && arg == 0)
2962 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2963 else
2964 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002965
John Kessenichb9197c82019-08-11 07:41:45 -06002966#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002967 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2968 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2969
2970 if (arg == 1) {
2971 // fold "element" parameter into the access chain
2972 spv::Builder::AccessChain save = builder.getAccessChain();
2973 builder.clearAccessChain();
2974 glslangOperands[2]->traverse(this);
2975
2976 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2977
2978 builder.setAccessChain(save);
2979
2980 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002981 builder.accessChainPush(elementId,
2982 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2983 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002984
2985 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2986 unsigned int alignment = builder.getAccessChain().alignment;
2987
2988 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2989 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2990 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2991 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2992 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002993 if (builder.getStorageClass(builder.getAccessChain().base) ==
2994 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002995 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2996 }
2997
2998 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2999
3000 if (memoryAccess & spv::MemoryAccessAlignedMask) {
3001 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
3002 }
3003
John Kessenich8985fc92020-03-03 10:25:07 -07003004 if (memoryAccess &
3005 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
3006 memoryAccessOperands.push_back(spv::IdImmediate(true,
3007 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003008 }
3009 } else if (arg == 2) {
3010 continue;
3011 }
3012 }
John Kessenichb9197c82019-08-11 07:41:45 -06003013#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003014
John Kessenichbbbd9a22020-03-03 07:21:37 -07003015 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003016 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07003017 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
3018 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
3019 // reduce to a simple access chain. So, we need a temporary vector to
3020 // receive the result, and must later swizzle that into the original
3021 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06003022 complexLvalues.push_back(builder.getAccessChain());
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003023 complexLValueQualifiers.push_back(glslangOperands[arg]->getAsTyped()->getType().getQualifier());
John Kessenich435dd802020-06-30 01:27:08 -06003024 temporaryLvalues.push_back(builder.createVariable(
3025 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003026 builder.accessChainGetInferredType(), "swizzleTemp"));
3027 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003028 } else {
3029 operands.push_back(builder.accessChainGetLValue());
3030 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003031 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3032 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3033 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003034 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003035 glslang::TOperator glslangOp = node->getOp();
3036 if (arg == 1 &&
3037 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3038 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3039 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3040 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3041 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3042 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3043 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3044 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3045 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3046 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3047 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3048 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3049 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3050 )) {
3051 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3052 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3053 }
3054 else {
3055 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3056 }
3057
John Kesseniche485c7a2017-05-31 18:50:53 -06003058 }
John Kessenich140f3df2015-06-26 16:58:36 -06003059 }
John Kessenich426394d2015-07-23 10:22:48 -06003060
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003061 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003062#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003063 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3064 std::vector<spv::IdImmediate> idImmOps;
3065
3066 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3067 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3068 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3069 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3070 // get the pointee type
3071 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3072 assert(builder.isCooperativeMatrixType(typeId));
3073 // do the op
3074 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3075 // store the result to the pointer (out param 'm')
3076 builder.createStore(result, operands[0]);
3077 result = 0;
3078 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3079 std::vector<spv::IdImmediate> idImmOps;
3080
3081 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3082 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3083 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3084 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3085 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3086
3087 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3088 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003089 } else
3090#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003091 if (atomic) {
3092 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003093 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3094 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003095 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3096 if (!nonSemanticDebugPrintf) {
3097 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3098 }
3099 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3100 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003101 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003102 // Pass through to generic operations.
3103 switch (glslangOperands.size()) {
3104 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003105 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003106 break;
3107 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003108 {
3109 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003110 TranslateNoContractionDecoration(node->getType().getQualifier()),
3111 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003112 result = createUnaryOperation(
3113 node->getOp(), decorations,
3114 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003115 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003116 }
John Kessenich426394d2015-07-23 10:22:48 -06003117 break;
3118 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003119 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003120 break;
3121 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003122
John Kessenichbbbd9a22020-03-03 07:21:37 -07003123 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003124 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003125
3126 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3127 builder.setAccessChain(complexLvalues[i]);
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003128 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision), TranslateNonUniformDecoration(complexLValueQualifiers[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003129 }
John Kessenich140f3df2015-06-26 16:58:36 -06003130 }
3131
3132 if (noReturnValue)
3133 return false;
3134
3135 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003136 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003137 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003138 } else {
3139 builder.clearAccessChain();
3140 builder.setAccessChainRValue(result);
3141 return false;
3142 }
3143}
3144
John Kessenich433e9ff2017-01-26 20:31:11 -07003145// This path handles both if-then-else and ?:
3146// The if-then-else has a node type of void, while
3147// ?: has either a void or a non-void node type
3148//
3149// Leaving the result, when not void:
3150// GLSL only has r-values as the result of a :?, but
3151// if we have an l-value, that can be more efficient if it will
3152// become the base of a complex r-value expression, because the
3153// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003154bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3155{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003156 // see if OpSelect can handle it
3157 const auto isOpSelectable = [&]() {
3158 if (node->getBasicType() == glslang::EbtVoid)
3159 return false;
3160 // OpSelect can do all other types starting with SPV 1.4
3161 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3162 // pre-1.4, only scalars and vectors can be handled
3163 if ((!node->getType().isScalar() && !node->getType().isVector()))
3164 return false;
3165 }
3166 return true;
3167 };
3168
John Kessenich4bee5312018-02-20 21:29:05 -07003169 // See if it simple and safe, or required, to execute both sides.
3170 // Crucially, side effects must be either semantically required or avoided,
3171 // and there are performance trade-offs.
3172 // Return true if required or a good idea (and safe) to execute both sides,
3173 // false otherwise.
3174 const auto bothSidesPolicy = [&]() -> bool {
3175 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003176 if (node->getTrueBlock() == nullptr ||
3177 node->getFalseBlock() == nullptr)
3178 return false;
3179
John Kessenich4bee5312018-02-20 21:29:05 -07003180 // required? (unless we write additional code to look for side effects
3181 // and make performance trade-offs if none are present)
3182 if (!node->getShortCircuit())
3183 return true;
3184
3185 // if not required to execute both, decide based on performance/practicality...
3186
John Kessenich0c1e71a2019-01-10 18:23:06 +07003187 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003188 return false;
3189
John Kessenich433e9ff2017-01-26 20:31:11 -07003190 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3191 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3192
3193 // return true if a single operand to ? : is okay for OpSelect
3194 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003195 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003196 };
3197
3198 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3199 operandOkay(node->getFalseBlock()->getAsTyped());
3200 };
3201
John Kessenich4bee5312018-02-20 21:29:05 -07003202 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3203 // emit the condition before doing anything with selection
3204 node->getCondition()->traverse(this);
3205 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3206
3207 // Find a way of executing both sides and selecting the right result.
3208 const auto executeBothSides = [&]() -> void {
3209 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003210 node->getTrueBlock()->traverse(this);
3211 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3212 node->getFalseBlock()->traverse(this);
3213 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3214
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003215 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003216
John Kessenich4bee5312018-02-20 21:29:05 -07003217 // done if void
3218 if (node->getBasicType() == glslang::EbtVoid)
3219 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003220
John Kessenich4bee5312018-02-20 21:29:05 -07003221 // emit code to select between trueValue and falseValue
3222
3223 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003224 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003225 // Emit OpSelect for this selection.
3226
3227 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003228 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3229 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003230 condition = builder.smearScalar(spv::NoPrecision, condition,
3231 builder.makeVectorType(builder.makeBoolType(),
3232 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003233 }
John Kessenich4bee5312018-02-20 21:29:05 -07003234
3235 // OpSelect
3236 result = builder.createTriOp(spv::OpSelect,
3237 convertGlslangToSpvType(node->getType()), condition,
3238 trueValue, falseValue);
3239
3240 builder.clearAccessChain();
3241 builder.setAccessChainRValue(result);
3242 } else {
3243 // We need control flow to select the result.
3244 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003245 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3246 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003247
3248 // Selection control:
3249 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3250
3251 // make an "if" based on the value created by the condition
3252 spv::Builder::If ifBuilder(condition, control, builder);
3253
3254 // emit the "then" statement
3255 builder.createStore(trueValue, result);
3256 ifBuilder.makeBeginElse();
3257 // emit the "else" statement
3258 builder.createStore(falseValue, result);
3259
3260 // finish off the control flow
3261 ifBuilder.makeEndIf();
3262
3263 builder.clearAccessChain();
3264 builder.setAccessChainLValue(result);
3265 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003266 };
3267
John Kessenich4bee5312018-02-20 21:29:05 -07003268 // Execute the one side needed, as per the condition
3269 const auto executeOneSide = [&]() {
3270 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003271 if (node->getBasicType() != glslang::EbtVoid) {
3272 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3273 convertGlslangToSpvType(node->getType()));
3274 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003275
John Kessenich4bee5312018-02-20 21:29:05 -07003276 // Selection control:
3277 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3278
3279 // make an "if" based on the value created by the condition
3280 spv::Builder::If ifBuilder(condition, control, builder);
3281
3282 // emit the "then" statement
3283 if (node->getTrueBlock() != nullptr) {
3284 node->getTrueBlock()->traverse(this);
3285 if (result != spv::NoResult)
3286 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3287 }
3288
3289 if (node->getFalseBlock() != nullptr) {
3290 ifBuilder.makeBeginElse();
3291 // emit the "else" statement
3292 node->getFalseBlock()->traverse(this);
3293 if (result != spv::NoResult)
3294 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3295 }
3296
3297 // finish off the control flow
3298 ifBuilder.makeEndIf();
3299
3300 if (result != spv::NoResult) {
3301 builder.clearAccessChain();
3302 builder.setAccessChainLValue(result);
3303 }
3304 };
3305
3306 // Try for OpSelect (or a requirement to execute both sides)
3307 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003308 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3309 if (node->getType().getQualifier().isSpecConstant())
3310 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003311 executeBothSides();
3312 } else
3313 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003314
3315 return false;
3316}
3317
3318bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3319{
3320 // emit and get the condition before doing anything with switch
3321 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003322 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003323
Rex Xu57e65922017-07-04 23:23:40 +08003324 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003325 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003326
John Kessenich140f3df2015-06-26 16:58:36 -06003327 // browse the children to sort out code segments
3328 int defaultSegment = -1;
3329 std::vector<TIntermNode*> codeSegments;
3330 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3331 std::vector<int> caseValues;
3332 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3333 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3334 TIntermNode* child = *c;
3335 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003336 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003337 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003338 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003339 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3340 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003341 } else
3342 codeSegments.push_back(child);
3343 }
3344
qining25262b32016-05-06 17:25:16 -04003345 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003346 // statements between the last case and the end of the switch statement
3347 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3348 (int)codeSegments.size() == defaultSegment)
3349 codeSegments.push_back(nullptr);
3350
3351 // make the switch statement
3352 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003353 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3354 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003355
3356 // emit all the code in the segments
3357 breakForLoop.push(false);
3358 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3359 builder.nextSwitchSegment(segmentBlocks, s);
3360 if (codeSegments[s])
3361 codeSegments[s]->traverse(this);
3362 else
3363 builder.addSwitchBreak();
3364 }
3365 breakForLoop.pop();
3366
3367 builder.endSwitch(segmentBlocks);
3368
3369 return false;
3370}
3371
3372void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3373{
3374 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003375 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003376
3377 builder.clearAccessChain();
3378 builder.setAccessChainRValue(constant);
3379}
3380
3381bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3382{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003383 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003384 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003385
3386 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003387 std::vector<unsigned int> operands;
3388 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003389
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003390 // Spec requires back edges to target header blocks, and every header block
3391 // must dominate its merge block. Make a header block first to ensure these
3392 // conditions are met. By definition, it will contain OpLoopMerge, followed
3393 // by a block-ending branch. But we don't want to put any other body/test
3394 // instructions in it, since the body/test may have arbitrary instructions,
3395 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003396 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003397 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003398 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003399 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003400 spv::Block& test = builder.makeNewBlock();
3401 builder.createBranch(&test);
3402
3403 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003404 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003405 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003406 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3407
3408 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003409 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003410 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003411 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003412 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003413 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003414
3415 builder.setBuildPoint(&blocks.continue_target);
3416 if (node->getTerminal())
3417 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003418 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003419 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003420 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003421 builder.createBranch(&blocks.body);
3422
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003423 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003424 builder.setBuildPoint(&blocks.body);
3425 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003426 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003427 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003428 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003429
3430 builder.setBuildPoint(&blocks.continue_target);
3431 if (node->getTerminal())
3432 node->getTerminal()->traverse(this);
3433 if (node->getTest()) {
3434 node->getTest()->traverse(this);
3435 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003436 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003437 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003438 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003439 // TODO: unless there was a break/return/discard instruction
3440 // somewhere in the body, this is an infinite loop, so we should
3441 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003442 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003443 }
John Kessenich140f3df2015-06-26 16:58:36 -06003444 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003445 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003446 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003447 return false;
3448}
3449
3450bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3451{
3452 if (node->getExpression())
3453 node->getExpression()->traverse(this);
3454
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003455 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003456
John Kessenich140f3df2015-06-26 16:58:36 -06003457 switch (node->getFlowOp()) {
3458 case glslang::EOpKill:
3459 builder.makeDiscard();
3460 break;
3461 case glslang::EOpBreak:
3462 if (breakForLoop.top())
3463 builder.createLoopExit();
3464 else
3465 builder.addSwitchBreak();
3466 break;
3467 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003468 builder.createLoopContinue();
3469 break;
3470 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003471 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003472 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3473 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003474 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3475 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003476 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003477 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3478 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003479 builder.setAccessChainLValue(copyId);
3480 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003481 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003482 }
3483 builder.makeReturn(false, returnId);
3484 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003485 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003486
3487 builder.clearAccessChain();
3488 break;
3489
John Kessenichb9197c82019-08-11 07:41:45 -06003490#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003491 case glslang::EOpDemote:
3492 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3493 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3494 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3495 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003496#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003497
John Kessenich140f3df2015-06-26 16:58:36 -06003498 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003499 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003500 break;
3501 }
3502
3503 return false;
3504}
3505
John Kessenich9c14f772019-06-17 08:38:35 -06003506spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003507{
qining25262b32016-05-06 17:25:16 -04003508 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003509 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003510 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003511 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003512 spv::Id result = createSpvConstant(*node);
3513 if (result != spv::NoResult)
3514 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003515 }
3516
3517 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003518 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003519 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3520 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003521
John Kessenichb9197c82019-08-11 07:41:45 -06003522 const bool contains16BitType = node->getType().contains16BitFloat() ||
3523 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003524 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003525 switch (storageClass) {
3526 case spv::StorageClassInput:
3527 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003528 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003529 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003530 break;
John Kessenich18310872018-05-14 22:08:53 -06003531 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003532 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003533 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3534 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003535 else
3536 builder.addCapability(spv::CapabilityStorageUniform16);
3537 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003538#ifndef GLSLANG_WEB
3539 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003540 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003541 builder.addCapability(spv::CapabilityStoragePushConstant16);
3542 break;
John Kessenich18310872018-05-14 22:08:53 -06003543 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003544 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003545 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003546 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3547 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003548#endif
John Kessenich18310872018-05-14 22:08:53 -06003549 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003550 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003551 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003552 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003553 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003554 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003555 }
3556 }
Rex Xuf89ad982017-04-07 23:22:33 +08003557
John Kessenichb9197c82019-08-11 07:41:45 -06003558 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003559 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003560 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003561 builder.addCapability(spv::CapabilityStoragePushConstant8);
3562 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003563 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003564 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003565 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003566 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003567 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003568 } else {
3569 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003570 }
3571 }
3572
John Kessenich140f3df2015-06-26 16:58:36 -06003573 const char* name = node->getName().c_str();
3574 if (glslang::IsAnonymous(name))
3575 name = "";
3576
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003577 spv::Id initializer = spv::NoResult;
3578
3579 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3580 !node->getConstArray().empty()) {
3581 int nextConst = 0;
3582 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3583 node->getConstArray(),
3584 nextConst,
3585 false /* specConst */);
3586 }
3587
John Kessenich435dd802020-06-30 01:27:08 -06003588 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003589}
3590
3591// Return type Id of the sampled type.
3592spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3593{
3594 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003595 case glslang::EbtInt: return builder.makeIntType(32);
3596 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003597 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003598#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003599 case glslang::EbtFloat16:
3600 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3601 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3602 return builder.makeFloatType(16);
Tobski8c1a3a02020-11-04 16:24:23 +00003603 case glslang::EbtInt64: return builder.makeIntType(64);
3604 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3605 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3606 case glslang::EbtUint64: return builder.makeUintType(64);
3607 builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
3608 builder.addCapability(spv::CapabilityFloat16ImageAMD);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003609#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003610 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003611 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003612 return builder.makeFloatType(32);
3613 }
3614}
3615
John Kessenich8c8505c2016-07-26 12:50:38 -06003616// If node is a swizzle operation, return the type that should be used if
3617// the swizzle base is first consumed by another operation, before the swizzle
3618// is applied.
3619spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3620{
John Kessenichecba76f2017-01-06 00:34:48 -07003621 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003622 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3623 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3624 else
3625 return spv::NoType;
3626}
3627
3628// When inverting a swizzle with a parent op, this function
3629// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003630spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3631 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003632{
3633 std::vector<unsigned> swizzle;
3634 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3635 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3636}
3637
John Kessenich8c8505c2016-07-26 12:50:38 -06003638// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3639void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3640{
3641 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3642 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3643 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3644}
3645
John Kessenich3ac051e2015-12-20 11:29:16 -07003646// Convert from a glslang type to an SPV type, by calling into a
3647// recursive version of this function. This establishes the inherited
3648// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003649spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003650{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003651 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003652}
3653
3654// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003655// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003656// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003657spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003658 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3659 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003660{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003661 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003662
3663 switch (type.getBasicType()) {
3664 case glslang::EbtVoid:
3665 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003666 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003667 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003668 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003669 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3670 // a 32-bit int where non-0 means true.
3671 if (explicitLayout != glslang::ElpNone)
3672 spvType = builder.makeUintType(32);
3673 else
3674 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003675 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003676 case glslang::EbtInt:
3677 spvType = builder.makeIntType(32);
3678 break;
3679 case glslang::EbtUint:
3680 spvType = builder.makeUintType(32);
3681 break;
3682 case glslang::EbtFloat:
3683 spvType = builder.makeFloatType(32);
3684 break;
3685#ifndef GLSLANG_WEB
3686 case glslang::EbtDouble:
3687 spvType = builder.makeFloatType(64);
3688 break;
3689 case glslang::EbtFloat16:
3690 spvType = builder.makeFloatType(16);
3691 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003692 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003693 spvType = builder.makeIntType(8);
3694 break;
3695 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003696 spvType = builder.makeUintType(8);
3697 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003698 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003699 spvType = builder.makeIntType(16);
3700 break;
3701 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003702 spvType = builder.makeUintType(16);
3703 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003704 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003705 spvType = builder.makeIntType(64);
3706 break;
3707 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003708 spvType = builder.makeUintType(64);
3709 break;
John Kessenich426394d2015-07-23 10:22:48 -06003710 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003711 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003712 spvType = builder.makeUintType(32);
3713 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003714 case glslang::EbtAccStruct:
3715 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003716 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003717 case glslang::EbtRayQuery:
3718 spvType = builder.makeRayQueryType();
3719 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003720 case glslang::EbtReference:
3721 {
3722 // Make the forward pointer, then recurse to convert the structure type, then
3723 // patch up the forward pointer with a real pointer type.
3724 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3725 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3726 forwardPointers[type.getReferentType()] = forwardId;
3727 }
3728 spvType = forwardPointers[type.getReferentType()];
3729 if (!forwardReferenceOnly) {
3730 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3731 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3732 forwardPointers[type.getReferentType()],
3733 referentType);
3734 }
3735 }
3736 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003737#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003738 case glslang::EbtSampler:
3739 {
3740 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003741 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003742 spvType = builder.makeSamplerType();
3743 } else {
3744 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003745 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3746 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3747 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3748 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003749 // already has both image and sampler, make the combined type
3750 spvType = builder.makeSampledImageType(spvType);
3751 }
John Kessenich55e7d112015-11-15 21:33:39 -07003752 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003753 }
John Kessenich140f3df2015-06-26 16:58:36 -06003754 break;
3755 case glslang::EbtStruct:
3756 case glslang::EbtBlock:
3757 {
3758 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003759 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003760
3761 // Try to share structs for different layouts, but not yet for other
3762 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003763 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003764 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003765 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003766 break;
3767
3768 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003769 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003770 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003771 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003772 }
3773 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003774 case glslang::EbtString:
3775 // no type used for OpString
3776 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003777 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003778 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003779 break;
3780 }
3781
3782 if (type.isMatrix())
3783 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3784 else {
3785 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3786 if (type.getVectorSize() > 1)
3787 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3788 }
3789
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003790 if (type.isCoopMat()) {
3791 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3792 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3793 if (type.getBasicType() == glslang::EbtFloat16)
3794 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003795 if (type.getBasicType() == glslang::EbtUint8 ||
3796 type.getBasicType() == glslang::EbtInt8) {
3797 builder.addCapability(spv::CapabilityInt8);
3798 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003799
3800 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3801 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3802 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3803
3804 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3805 }
3806
John Kessenich140f3df2015-06-26 16:58:36 -06003807 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003808 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3809
John Kessenichc9a80832015-09-12 12:17:44 -06003810 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003811 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003812 // We need to decorate array strides for types needing explicit layout, except blocks.
3813 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003814 // Use a dummy glslang type for querying internal strides of
3815 // arrays of arrays, but using just a one-dimensional array.
3816 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003817 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3818 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003819
3820 // Will compute the higher-order strides here, rather than making a whole
3821 // pile of types and doing repetitive recursion on their contents.
3822 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3823 }
John Kessenichf8842e52016-01-04 19:22:56 -07003824
3825 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003826 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003827 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003828 if (stride > 0)
3829 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003830 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003831 }
3832 } else {
3833 // single-dimensional array, and don't yet have stride
3834
John Kessenichf8842e52016-01-04 19:22:56 -07003835 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003836 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3837 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003838 }
John Kessenich31ed4832015-09-09 17:51:38 -06003839
John Kessenichead86222018-03-28 18:01:20 -06003840 // Do the outer dimension, which might not be known for a runtime-sized array.
3841 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3842 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003843 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003844 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003845#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003846 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003847 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003848 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3849 }
John Kessenichb9197c82019-08-11 07:41:45 -06003850#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003851 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003852 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003853 if (stride > 0)
3854 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003855 }
3856
3857 return spvType;
3858}
3859
John Kessenich0e737842017-03-24 18:38:16 -06003860// TODO: this functionality should exist at a higher level, in creating the AST
3861//
3862// Identify interface members that don't have their required extension turned on.
3863//
3864bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3865{
John Kessenicha28f7a72019-08-06 07:00:58 -06003866#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003867 auto& extensions = glslangIntermediate->getRequestedExtensions();
3868
Rex Xubcf291a2017-03-29 23:01:36 +08003869 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3870 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3871 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003872 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3873 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3874 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003875
3876 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3877 if (member.getFieldName() == "gl_ViewportMask" &&
3878 extensions.find("GL_NV_viewport_array2") == extensions.end())
3879 return true;
3880 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3881 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3882 return true;
3883 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3884 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3885 return true;
3886 }
3887#endif
John Kessenich0e737842017-03-24 18:38:16 -06003888
3889 return false;
3890};
3891
John Kessenich6090df02016-06-30 21:18:02 -06003892// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3893// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3894// Mutually recursive with convertGlslangToSpvType().
3895spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3896 const glslang::TTypeList* glslangMembers,
3897 glslang::TLayoutPacking explicitLayout,
3898 const glslang::TQualifier& qualifier)
3899{
3900 // Create a vector of struct types for SPIR-V to consume
3901 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003902 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3903 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003904 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003905 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3906 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3907 if (glslangMember.hiddenMember()) {
3908 ++memberDelta;
3909 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003910 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003911 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003912 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003913 if (filterMember(glslangMember)) {
3914 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003915 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003916 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003917 }
Roy05a5b532020-01-03 16:21:34 +08003918 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003919 }
John Kessenich6090df02016-06-30 21:18:02 -06003920 // modify just this child's view of the qualifier
3921 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3922 InheritQualifiers(memberQualifier, qualifier);
3923
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003924 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003925 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003926 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003927
3928 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003929 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3930 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003931
3932 // Make forward pointers for any pointer members, and create a list of members to
3933 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003934 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003935 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3936 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3937 }
3938 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003939 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3940 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003941 } else {
3942 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003943 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3944 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003945 }
John Kessenich6090df02016-06-30 21:18:02 -06003946 }
3947 }
3948
3949 // Make the SPIR-V type
3950 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003951 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003952 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3953
3954 // Decorate it
3955 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3956
John Kessenichd72f4882019-01-16 14:55:37 +07003957 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003958 auto it = deferredForwardPointers[i];
3959 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3960 }
3961
John Kessenich6090df02016-06-30 21:18:02 -06003962 return spvType;
3963}
3964
3965void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3966 const glslang::TTypeList* glslangMembers,
3967 glslang::TLayoutPacking explicitLayout,
3968 const glslang::TQualifier& qualifier,
3969 spv::Id spvType)
3970{
3971 // Name and decorate the non-hidden members
3972 int offset = -1;
3973 int locationOffset = 0; // for use within the members of this struct
Chow478b2322020-11-04 04:34:19 +08003974 bool memberLocationInvalid = type.isArrayOfArrays() ||
3975 (type.isArray() && (type.getQualifier().isArrayedIo(glslangIntermediate->getStage()) == false));
John Kessenich6090df02016-06-30 21:18:02 -06003976 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3977 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3978 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003979 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003980 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003981 if (filterMember(glslangMember))
3982 continue;
3983 }
John Kessenich6090df02016-06-30 21:18:02 -06003984
3985 // modify just this child's view of the qualifier
3986 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3987 InheritQualifiers(memberQualifier, qualifier);
3988
3989 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003990 if (member < 0)
3991 continue;
3992
3993 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3994 builder.addMemberDecoration(spvType, member,
3995 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3996 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3997 // Add interpolation and auxiliary storage decorations only to
3998 // top-level members of Input and Output storage classes
3999 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
4000 type.getQualifier().storage == glslang::EvqVaryingOut) {
4001 if (type.getBasicType() == glslang::EbtBlock ||
4002 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
4003 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
4004 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06004005#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07004006 addMeshNVDecoration(spvType, member, memberQualifier);
4007#endif
John Kessenich6090df02016-06-30 21:18:02 -06004008 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004009 }
4010 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06004011
John Kessenichb9197c82019-08-11 07:41:45 -06004012#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07004013 if (type.getBasicType() == glslang::EbtBlock &&
4014 qualifier.storage == glslang::EvqBuffer) {
4015 // Add memory decorations only to top-level members of shader storage block
4016 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05004017 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07004018 for (unsigned int i = 0; i < memory.size(); ++i)
4019 builder.addMemberDecoration(spvType, member, memory[i]);
4020 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004021
John Kessenichb9197c82019-08-11 07:41:45 -06004022#endif
John Kessenich6090df02016-06-30 21:18:02 -06004023
John Kessenich5d610ee2018-03-07 18:05:55 -07004024 // Location assignment was already completed correctly by the front end,
4025 // just track whether a member needs to be decorated.
4026 // Ignore member locations if the container is an array, as that's
4027 // ill-specified and decisions have been made to not allow this.
Chow478b2322020-11-04 04:34:19 +08004028 if (!memberLocationInvalid && memberQualifier.hasLocation())
John Kessenich5d610ee2018-03-07 18:05:55 -07004029 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004030
John Kessenich5d610ee2018-03-07 18:05:55 -07004031 if (qualifier.hasLocation()) // track for upcoming inheritance
4032 locationOffset += glslangIntermediate->computeTypeLocationSize(
4033 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004034
John Kessenich5d610ee2018-03-07 18:05:55 -07004035 // component, XFB, others
4036 if (glslangMember.getQualifier().hasComponent())
4037 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4038 glslangMember.getQualifier().layoutComponent);
4039 if (glslangMember.getQualifier().hasXfbOffset())
4040 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4041 glslangMember.getQualifier().layoutXfbOffset);
4042 else if (explicitLayout != glslang::ElpNone) {
4043 // figure out what to do with offset, which is accumulating
4044 int nextOffset;
4045 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4046 if (offset >= 0)
4047 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4048 offset = nextOffset;
4049 }
John Kessenich6090df02016-06-30 21:18:02 -06004050
John Kessenich5d610ee2018-03-07 18:05:55 -07004051 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4052 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4053 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004054
John Kessenich5d610ee2018-03-07 18:05:55 -07004055 // built-in variable decorations
4056 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4057 if (builtIn != spv::BuiltInMax)
4058 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004059
John Kessenichb9197c82019-08-11 07:41:45 -06004060#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004061 // nonuniform
4062 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4063
John Kessenichead86222018-03-28 18:01:20 -06004064 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4065 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4066 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4067 memberQualifier.semanticName);
4068 }
4069
John Kessenich5d610ee2018-03-07 18:05:55 -07004070 if (builtIn == spv::BuiltInLayer) {
4071 // SPV_NV_viewport_array2 extension
4072 if (glslangMember.getQualifier().layoutViewportRelative){
4073 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4074 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4075 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004076 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004077 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4078 builder.addMemberDecoration(spvType, member,
4079 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4080 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4081 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4082 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004083 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004084 }
4085 if (glslangMember.getQualifier().layoutPassthrough) {
4086 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4087 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4088 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4089 }
chaoc771d89f2017-01-13 01:10:53 -08004090#endif
John Kessenich6090df02016-06-30 21:18:02 -06004091 }
4092
4093 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004094 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4095 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004096}
4097
John Kessenich6c292d32016-02-15 20:58:50 -07004098// Turn the expression forming the array size into an id.
4099// This is not quite trivial, because of specialization constants.
4100// Sometimes, a raw constant is turned into an Id, and sometimes
4101// a specialization constant expression is.
4102spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4103{
4104 // First, see if this is sized with a node, meaning a specialization constant:
4105 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4106 if (specNode != nullptr) {
4107 builder.clearAccessChain();
4108 specNode->traverse(this);
4109 return accessChainLoad(specNode->getAsTyped()->getType());
4110 }
qining25262b32016-05-06 17:25:16 -04004111
John Kessenich6c292d32016-02-15 20:58:50 -07004112 // Otherwise, need a compile-time (front end) size, get it:
4113 int size = arraySizes.getDimSize(dim);
4114 assert(size > 0);
4115 return builder.makeUintConstant(size);
4116}
4117
John Kessenich103bef92016-02-08 21:38:15 -07004118// Wrap the builder's accessChainLoad to:
4119// - localize handling of RelaxedPrecision
4120// - use the SPIR-V inferred type instead of another conversion of the glslang type
4121// (avoids unnecessary work and possible type punning for structures)
4122// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004123spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4124{
John Kessenich103bef92016-02-08 21:38:15 -07004125 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004126
4127 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4128 coherentFlags |= TranslateCoherent(type);
4129
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004130 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004131 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004132
John Kessenich5611c6d2018-04-05 11:25:02 -06004133 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004134 TranslateNonUniformDecoration(type.getQualifier()),
4135 nominalTypeId,
4136 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4137 TranslateMemoryScope(coherentFlags),
4138 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004139
4140 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004141 if (type.getBasicType() == glslang::EbtBool) {
4142 if (builder.isScalarType(nominalTypeId)) {
4143 // Conversion for bool
4144 spv::Id boolType = builder.makeBoolType();
4145 if (nominalTypeId != boolType)
4146 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4147 } else if (builder.isVectorType(nominalTypeId)) {
4148 // Conversion for bvec
4149 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4150 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4151 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004152 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4153 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004154 }
4155 }
John Kessenich103bef92016-02-08 21:38:15 -07004156
4157 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004158}
4159
Rex Xu27253232016-02-23 17:51:09 +08004160// Wrap the builder's accessChainStore to:
4161// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004162//
4163// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004164void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4165{
4166 // Need to convert to abstract types when necessary
4167 if (type.getBasicType() == glslang::EbtBool) {
4168 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4169
4170 if (builder.isScalarType(nominalTypeId)) {
4171 // Conversion for bool
4172 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004173 if (nominalTypeId != boolType) {
4174 // keep these outside arguments, for determinant order-of-evaluation
4175 spv::Id one = builder.makeUintConstant(1);
4176 spv::Id zero = builder.makeUintConstant(0);
4177 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4178 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004179 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004180 } else if (builder.isVectorType(nominalTypeId)) {
4181 // Conversion for bvec
4182 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4183 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004184 if (nominalTypeId != bvecType) {
4185 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004186 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4187 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4188 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004189 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004190 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4191 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004192 }
4193 }
4194
Jeff Bolz36831c92018-09-05 10:11:41 -05004195 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4196 coherentFlags |= TranslateCoherent(type);
4197
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004198 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004199 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004200
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02004201 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(type.getQualifier()),
John Kessenich8985fc92020-03-03 10:25:07 -07004202 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4203 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004204 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004205}
4206
John Kessenich4bf71552016-09-02 11:20:21 -06004207// For storing when types match at the glslang level, but not might match at the
4208// SPIR-V level.
4209//
4210// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004211// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004212// as in a member-decorated way.
4213//
4214// NOTE: This function can handle any store request; if it's not special it
4215// simplifies to a simple OpStore.
4216//
4217// Implicitly uses the existing builder.accessChain as the storage target.
4218void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4219{
John Kessenichb3e24e42016-09-11 12:33:43 -06004220 // we only do the complex path here if it's an aggregate
4221 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004222 accessChainStore(type, rValue);
4223 return;
4224 }
4225
John Kessenichb3e24e42016-09-11 12:33:43 -06004226 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004227 spv::Id rType = builder.getTypeId(rValue);
4228 spv::Id lValue = builder.accessChainGetLValue();
4229 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4230 if (lType == rType) {
4231 accessChainStore(type, rValue);
4232 return;
4233 }
4234
John Kessenichb3e24e42016-09-11 12:33:43 -06004235 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004236 // where the two types were the same type in GLSL. This requires member
4237 // by member copy, recursively.
4238
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004239 // SPIR-V 1.4 added an instruction to do help do this.
4240 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4241 // However, bool in uniform space is changed to int, so
4242 // OpCopyLogical does not work for that.
4243 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4244 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4245 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4246 if (lBool == rBool) {
4247 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4248 accessChainStore(type, logicalCopy);
4249 return;
4250 }
4251 }
4252
John Kessenichb3e24e42016-09-11 12:33:43 -06004253 // If an array, copy element by element.
4254 if (type.isArray()) {
4255 glslang::TType glslangElementType(type, 0);
4256 spv::Id elementRType = builder.getContainedTypeId(rType);
4257 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4258 // get the source member
4259 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004260
John Kessenichb3e24e42016-09-11 12:33:43 -06004261 // set up the target storage
4262 builder.clearAccessChain();
4263 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004264 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4265 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004266
John Kessenichb3e24e42016-09-11 12:33:43 -06004267 // store the member
4268 multiTypeStore(glslangElementType, elementRValue);
4269 }
4270 } else {
4271 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004272
John Kessenichb3e24e42016-09-11 12:33:43 -06004273 // loop over structure members
4274 const glslang::TTypeList& members = *type.getStruct();
4275 for (int m = 0; m < (int)members.size(); ++m) {
4276 const glslang::TType& glslangMemberType = *members[m].type;
4277
4278 // get the source member
4279 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4280 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4281
4282 // set up the target storage
4283 builder.clearAccessChain();
4284 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004285 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4286 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004287
4288 // store the member
4289 multiTypeStore(glslangMemberType, memberRValue);
4290 }
John Kessenich4bf71552016-09-02 11:20:21 -06004291 }
4292}
4293
John Kessenichf85e8062015-12-19 13:57:10 -07004294// Decide whether or not this type should be
4295// decorated with offsets and strides, and if so
4296// whether std140 or std430 rules should be applied.
4297glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004298{
John Kessenichf85e8062015-12-19 13:57:10 -07004299 // has to be a block
4300 if (type.getBasicType() != glslang::EbtBlock)
4301 return glslang::ElpNone;
4302
Chao Chen3c366992018-09-19 11:41:59 -07004303 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004304 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004305 type.getQualifier().storage != glslang::EvqBuffer &&
4306 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004307 return glslang::ElpNone;
4308
4309 // return the layout to use
4310 switch (type.getQualifier().layoutPacking) {
4311 case glslang::ElpStd140:
4312 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004313 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004314 return type.getQualifier().layoutPacking;
4315 default:
4316 return glslang::ElpNone;
4317 }
John Kessenich31ed4832015-09-09 17:51:38 -06004318}
4319
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004320// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004321int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4322 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004323{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004324 int size;
John Kessenich49987892015-12-29 17:11:44 -07004325 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004326 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4327 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004328
4329 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004330}
4331
John Kessenich49987892015-12-29 17:11:44 -07004332// 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 -07004333// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004334int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4335 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004336{
John Kessenich49987892015-12-29 17:11:44 -07004337 glslang::TType elementType;
4338 elementType.shallowCopy(matrixType);
4339 elementType.clearArraySizes();
4340
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004341 int size;
John Kessenich49987892015-12-29 17:11:44 -07004342 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004343 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4344 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004345
4346 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004347}
4348
John Kessenich5e4b1242015-08-06 22:53:06 -06004349// Given a member type of a struct, realign the current offset for it, and compute
4350// the next (not yet aligned) offset for the next member, which will get aligned
4351// on the next call.
4352// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4353// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4354// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004355void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4356 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004357{
4358 // this will get a positive value when deemed necessary
4359 nextOffset = -1;
4360
John Kessenich5e4b1242015-08-06 22:53:06 -06004361 // override anything in currentOffset with user-set offset
4362 if (memberType.getQualifier().hasOffset())
4363 currentOffset = memberType.getQualifier().layoutOffset;
4364
4365 // It could be that current linker usage in glslang updated all the layoutOffset,
4366 // in which case the following code does not matter. But, that's not quite right
4367 // once cross-compilation unit GLSL validation is done, as the original user
4368 // settings are needed in layoutOffset, and then the following will come into play.
4369
John Kessenichf85e8062015-12-19 13:57:10 -07004370 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004371 if (! memberType.getQualifier().hasOffset())
4372 currentOffset = -1;
4373
4374 return;
4375 }
4376
John Kessenichf85e8062015-12-19 13:57:10 -07004377 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004378 if (currentOffset < 0)
4379 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004380
John Kessenich5e4b1242015-08-06 22:53:06 -06004381 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4382 // but possibly not yet correctly aligned.
4383
4384 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004385 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004386 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4387 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004388
4389 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004390 // TODO: make this consistent in early phases of code:
4391 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4392 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4393 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004394 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004395 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004396 int dummySize;
4397 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4398 if (componentAlignment <= 4)
4399 memberAlignment = componentAlignment;
4400 }
4401
4402 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004403 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004404
4405 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004406 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4407 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004408 glslang::RoundToPow2(currentOffset, 16);
4409
John Kessenich5e4b1242015-08-06 22:53:06 -06004410 nextOffset = currentOffset + memberSize;
4411}
4412
David Netoa901ffe2016-06-08 14:11:40 +01004413void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004414{
David Netoa901ffe2016-06-08 14:11:40 +01004415 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4416 switch (glslangBuiltIn)
4417 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004418 case glslang::EbvPointSize:
4419#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004420 case glslang::EbvClipDistance:
4421 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004422 case glslang::EbvViewportMaskNV:
4423 case glslang::EbvSecondaryPositionNV:
4424 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004425 case glslang::EbvPositionPerViewNV:
4426 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004427 case glslang::EbvTaskCountNV:
4428 case glslang::EbvPrimitiveCountNV:
4429 case glslang::EbvPrimitiveIndicesNV:
4430 case glslang::EbvClipDistancePerViewNV:
4431 case glslang::EbvCullDistancePerViewNV:
4432 case glslang::EbvLayerPerViewNV:
4433 case glslang::EbvMeshViewCountNV:
4434 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004435#endif
David Netoa901ffe2016-06-08 14:11:40 +01004436 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4437 // Alternately, we could just call this for any glslang built-in, since the
4438 // capability already guards against duplicates.
4439 TranslateBuiltInDecoration(glslangBuiltIn, false);
4440 break;
4441 default:
4442 // Capabilities were already generated when the struct was declared.
4443 break;
4444 }
John Kessenichebb50532016-05-16 19:22:05 -06004445}
4446
John Kessenich6fccb3c2016-09-19 16:01:41 -06004447bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004448{
John Kessenicheee9d532016-09-19 18:09:30 -06004449 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004450}
4451
John Kessenichd41993d2017-09-10 15:21:05 -06004452// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004453// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4454// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004455bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004456{
John Kessenich6a14f782017-12-04 02:48:10 -07004457 assert(qualifier == glslang::EvqIn ||
4458 qualifier == glslang::EvqOut ||
4459 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004460 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004461 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004462 return qualifier != glslang::EvqConstReadOnly &&
4463 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004464}
4465
4466// Is parameter pass-by-original?
4467bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4468 bool implicitThisParam)
4469{
4470 if (implicitThisParam) // implicit this
4471 return true;
4472 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004473 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004474 return paramType.containsOpaque() || // sampler, etc.
4475 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4476}
4477
John Kessenich140f3df2015-06-26 16:58:36 -06004478// Make all the functions, skeletally, without actually visiting their bodies.
4479void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4480{
John Kessenich8985fc92020-03-03 10:25:07 -07004481 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4482 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004483 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4484 if (paramPrecision != spv::NoPrecision)
4485 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004486 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004487 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004488 // Original and non-writable params pass the pointer directly and
4489 // use restrict/aliased, others are stored to a pointer in Function
4490 // memory and use RestrictPointer/AliasedPointer.
4491 if (originalParam(type.getQualifier().storage, type, false) ||
4492 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004493 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4494 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004495 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004496 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4497 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004498 }
4499 }
John Kessenichfad62972017-07-18 02:35:46 -06004500 };
4501
John Kessenich140f3df2015-06-26 16:58:36 -06004502 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4503 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004504 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004505 continue;
4506
4507 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004508 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004509 //
qining25262b32016-05-06 17:25:16 -04004510 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004511 // function. What it is an address of varies:
4512 //
John Kessenich4bf71552016-09-02 11:20:21 -06004513 // - "in" parameters not marked as "const" can be written to without modifying the calling
4514 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004515 //
4516 // - "const in" parameters can just be the r-value, as no writes need occur.
4517 //
John Kessenich4bf71552016-09-02 11:20:21 -06004518 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4519 // 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 -06004520
4521 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004522 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004523 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4524
John Kessenich155d3512019-08-08 23:29:20 -06004525#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004526 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4527 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004528#else
4529 bool implicitThis = false;
4530#endif
John Kessenich37789792017-03-21 23:56:40 -06004531
John Kessenichfad62972017-07-18 02:35:46 -06004532 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004533 for (int p = 0; p < (int)parameters.size(); ++p) {
4534 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4535 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004536 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004537 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004538 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004539 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4540 else
John Kessenich4bf71552016-09-02 11:20:21 -06004541 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004542 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004543 paramTypes.push_back(typeId);
4544 }
4545
4546 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004547 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4548 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004549 glslFunction->getName().c_str(), paramTypes,
4550 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004551 if (implicitThis)
4552 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004553
4554 // Track function to emit/call later
4555 functionMap[glslFunction->getName().c_str()] = function;
4556
4557 // Set the parameter id's
4558 for (int p = 0; p < (int)parameters.size(); ++p) {
4559 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4560 // give a name too
4561 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004562
4563 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004564 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004565 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004566 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004567 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004568 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004569 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004570 }
4571 }
4572}
4573
4574// Process all the initializers, while skipping the functions and link objects
4575void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4576{
4577 builder.setBuildPoint(shaderEntry->getLastBlock());
4578 for (int i = 0; i < (int)initializers.size(); ++i) {
4579 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004580 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4581 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004582
4583 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004584 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004585 initializer->traverse(this);
4586 }
4587 }
4588}
4589
4590// Process all the functions, while skipping initializers.
4591void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4592{
4593 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4594 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004595 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004596 node->traverse(this);
4597 }
4598}
4599
4600void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4601{
qining25262b32016-05-06 17:25:16 -04004602 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004603 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004604 currentFunction = functionMap[node->getName().c_str()];
4605 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004606 builder.setBuildPoint(functionBlock);
4607}
4608
John Kessenich8985fc92020-03-03 10:25:07 -07004609void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4610 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004611{
Rex Xufc618912015-09-09 16:42:49 +08004612 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004613
4614 glslang::TSampler sampler = {};
4615 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004616#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004617 bool f16ShadowCompare = false;
4618#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004619 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004620 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4621 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004622#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004623 f16ShadowCompare = sampler.shadow &&
4624 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004625#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004626 }
4627
John Kessenich140f3df2015-06-26 16:58:36 -06004628 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4629 builder.clearAccessChain();
4630 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004631
John Kessenicha28f7a72019-08-06 07:00:58 -06004632#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004633 // Special case l-value operands
4634 bool lvalue = false;
4635 switch (node.getOp()) {
4636 case glslang::EOpImageAtomicAdd:
4637 case glslang::EOpImageAtomicMin:
4638 case glslang::EOpImageAtomicMax:
4639 case glslang::EOpImageAtomicAnd:
4640 case glslang::EOpImageAtomicOr:
4641 case glslang::EOpImageAtomicXor:
4642 case glslang::EOpImageAtomicExchange:
4643 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004644 case glslang::EOpImageAtomicLoad:
4645 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004646 if (i == 0)
4647 lvalue = true;
4648 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004649 case glslang::EOpSparseImageLoad:
4650 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4651 lvalue = true;
4652 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004653 case glslang::EOpSparseTexture:
4654 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4655 lvalue = true;
4656 break;
4657 case glslang::EOpSparseTextureClamp:
4658 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4659 lvalue = true;
4660 break;
4661 case glslang::EOpSparseTextureLod:
4662 case glslang::EOpSparseTextureOffset:
4663 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4664 lvalue = true;
4665 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004666 case glslang::EOpSparseTextureFetch:
4667 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4668 lvalue = true;
4669 break;
4670 case glslang::EOpSparseTextureFetchOffset:
4671 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4672 lvalue = true;
4673 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004674 case glslang::EOpSparseTextureLodOffset:
4675 case glslang::EOpSparseTextureGrad:
4676 case glslang::EOpSparseTextureOffsetClamp:
4677 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4678 lvalue = true;
4679 break;
4680 case glslang::EOpSparseTextureGradOffset:
4681 case glslang::EOpSparseTextureGradClamp:
4682 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4683 lvalue = true;
4684 break;
4685 case glslang::EOpSparseTextureGradOffsetClamp:
4686 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4687 lvalue = true;
4688 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004689 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004690 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4691 lvalue = true;
4692 break;
4693 case glslang::EOpSparseTextureGatherOffset:
4694 case glslang::EOpSparseTextureGatherOffsets:
4695 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4696 lvalue = true;
4697 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004698 case glslang::EOpSparseTextureGatherLod:
4699 if (i == 3)
4700 lvalue = true;
4701 break;
4702 case glslang::EOpSparseTextureGatherLodOffset:
4703 case glslang::EOpSparseTextureGatherLodOffsets:
4704 if (i == 4)
4705 lvalue = true;
4706 break;
Rex Xu129799a2017-07-05 17:23:28 +08004707 case glslang::EOpSparseImageLoadLod:
4708 if (i == 3)
4709 lvalue = true;
4710 break;
Chao Chen3a137962018-09-19 11:41:27 -07004711 case glslang::EOpImageSampleFootprintNV:
4712 if (i == 4)
4713 lvalue = true;
4714 break;
4715 case glslang::EOpImageSampleFootprintClampNV:
4716 case glslang::EOpImageSampleFootprintLodNV:
4717 if (i == 5)
4718 lvalue = true;
4719 break;
4720 case glslang::EOpImageSampleFootprintGradNV:
4721 if (i == 6)
4722 lvalue = true;
4723 break;
4724 case glslang::EOpImageSampleFootprintGradClampNV:
4725 if (i == 7)
4726 lvalue = true;
4727 break;
Rex Xufc618912015-09-09 16:42:49 +08004728 default:
4729 break;
4730 }
4731
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004732 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004733 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004734 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4735 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4736 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004737#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004738 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004739 }
4740}
4741
John Kessenichfc51d282015-08-19 13:34:18 -06004742void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004743{
John Kessenichfc51d282015-08-19 13:34:18 -06004744 builder.clearAccessChain();
4745 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004746 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004747}
John Kessenich140f3df2015-06-26 16:58:36 -06004748
John Kessenichfc51d282015-08-19 13:34:18 -06004749spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4750{
John Kesseniche485c7a2017-05-31 18:50:53 -06004751 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004752 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004753
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004754 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004755
John Kessenichfc51d282015-08-19 13:34:18 -06004756 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004757
John Kessenichf43c7392019-03-31 10:51:57 -06004758 const glslang::TType &imageType = node->getAsAggregate()
4759 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4760 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004761 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004762#ifdef GLSLANG_WEB
4763 const bool f16ShadowCompare = false;
4764#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004765 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004766 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4767 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004768#endif
4769
John Kessenichf43c7392019-03-31 10:51:57 -06004770 const auto signExtensionMask = [&]() {
4771 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4772 if (sampler.type == glslang::EbtUint)
4773 return spv::ImageOperandsZeroExtendMask;
4774 else if (sampler.type == glslang::EbtInt)
4775 return spv::ImageOperandsSignExtendMask;
4776 }
4777 return spv::ImageOperandsMaskNone;
4778 };
4779
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004780 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4781
John Kessenichfc51d282015-08-19 13:34:18 -06004782 std::vector<spv::Id> arguments;
4783 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004784 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004785 else
4786 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004787 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004788
4789 spv::Builder::TextureParameters params = { };
4790 params.sampler = arguments[0];
4791
Rex Xu04db3f52015-09-16 11:44:02 +08004792 glslang::TCrackedTextureOp cracked;
4793 node->crackTexture(sampler, cracked);
4794
amhagan05506bb2017-06-13 16:53:02 -04004795 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004796
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004797 if (builder.isSampledImage(params.sampler) &&
4798 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4799 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4800 if (imageType.getQualifier().isNonUniform()) {
4801 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4802 }
4803 }
John Kessenichfc51d282015-08-19 13:34:18 -06004804 // Check for queries
4805 if (cracked.query) {
4806 switch (node->getOp()) {
4807 case glslang::EOpImageQuerySize:
4808 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004809 if (arguments.size() > 1) {
4810 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004811 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004812 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004813 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004814#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004815 case glslang::EOpImageQuerySamples:
4816 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004817 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004818 case glslang::EOpTextureQueryLod:
4819 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004820 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004821 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004822 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004823 case glslang::EOpSparseTexelsResident:
4824 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004825#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004826 default:
4827 assert(0);
4828 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004829 }
John Kessenich140f3df2015-06-26 16:58:36 -06004830 }
4831
LoopDawg4425f242018-02-18 11:40:01 -07004832 int components = node->getType().getVectorSize();
4833
4834 if (node->getOp() == glslang::EOpTextureFetch) {
4835 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4836 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4837 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4838 // here around e.g. which ones return scalars or other types.
4839 components = 4;
4840 }
4841
4842 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4843
4844 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4845
Rex Xufc618912015-09-09 16:42:49 +08004846 // Check for image functions other than queries
4847 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004848 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004849 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004850 spv::IdImmediate image = { true, *(opIt++) };
4851 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004852
4853 // Handle subpass operations
4854 // TODO: GLSL should change to have the "MS" only on the type rather than the
4855 // built-in function.
4856 if (cracked.subpass) {
4857 // add on the (0,0) coordinate
4858 spv::Id zero = builder.makeIntConstant(0);
4859 std::vector<spv::Id> comps;
4860 comps.push_back(zero);
4861 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004862 spv::IdImmediate coord = { true,
4863 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4864 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004865 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4866 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004867 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004868 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4869 }
4870 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004871 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004872 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004873 spv::IdImmediate imageOperand = { true, *(opIt++) };
4874 operands.push_back(imageOperand);
4875 }
John Kessenich6c292d32016-02-15 20:58:50 -07004876 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004877 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4878 builder.setPrecision(result, precision);
4879 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004880 }
4881
John Kessenich149afc32018-08-14 13:31:43 -06004882 spv::IdImmediate coord = { true, *(opIt++) };
4883 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004884 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004885 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004886 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004887 mask = mask | spv::ImageOperandsSampleMask;
4888 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004889 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004890 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4891 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004892 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004893 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004894 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4895 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004896 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004897 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004898 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4899 operands.push_back(imageOperands);
4900 }
4901 if (mask & spv::ImageOperandsSampleMask) {
4902 spv::IdImmediate imageOperand = { true, *opIt++ };
4903 operands.push_back(imageOperand);
4904 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004905 if (mask & spv::ImageOperandsLodMask) {
4906 spv::IdImmediate imageOperand = { true, *opIt++ };
4907 operands.push_back(imageOperand);
4908 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004909 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004910 spv::IdImmediate imageOperand = { true,
4911 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004912 operands.push_back(imageOperand);
4913 }
4914
John Kessenich149afc32018-08-14 13:31:43 -06004915 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004916 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004917
John Kessenich149afc32018-08-14 13:31:43 -06004918 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004919 builder.setPrecision(result[0], precision);
4920
4921 // If needed, add a conversion constructor to the proper size.
4922 if (components != node->getType().getVectorSize())
4923 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4924
4925 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004926 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004927
Jeff Bolz36831c92018-09-05 10:11:41 -05004928 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004929 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004930 spv::IdImmediate texel = { true, *(opIt + 1) };
4931 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004932 } else {
4933 spv::IdImmediate texel = { true, *opIt };
4934 operands.push_back(texel);
4935 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004936
4937 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004938 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004939 mask = mask | spv::ImageOperandsSampleMask;
4940 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004941 if (cracked.lod) {
4942 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4943 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4944 mask = mask | spv::ImageOperandsLodMask;
4945 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004946 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4947 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004948 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004949 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004950 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4951 operands.push_back(imageOperands);
4952 }
4953 if (mask & spv::ImageOperandsSampleMask) {
4954 spv::IdImmediate imageOperand = { true, *opIt++ };
4955 operands.push_back(imageOperand);
4956 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004957 if (mask & spv::ImageOperandsLodMask) {
4958 spv::IdImmediate imageOperand = { true, *opIt++ };
4959 operands.push_back(imageOperand);
4960 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004961 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004962 spv::IdImmediate imageOperand = { true,
4963 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004964 operands.push_back(imageOperand);
4965 }
4966
John Kessenich56bab042015-09-16 10:54:31 -06004967 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004968 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004969 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004970 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004971 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4972 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004973 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004974 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004975 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4976
Jeff Bolz36831c92018-09-05 10:11:41 -05004977 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004978 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004979 mask = mask | spv::ImageOperandsSampleMask;
4980 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004981 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004982 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4983 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4984
Jeff Bolz36831c92018-09-05 10:11:41 -05004985 mask = mask | spv::ImageOperandsLodMask;
4986 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004987 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4988 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004989 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004990 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004991 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004992 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004993 }
4994 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004995 spv::IdImmediate imageOperand = { true, *opIt++ };
4996 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004997 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004998 if (mask & spv::ImageOperandsLodMask) {
4999 spv::IdImmediate imageOperand = { true, *opIt++ };
5000 operands.push_back(imageOperand);
5001 }
Jeff Bolz36831c92018-09-05 10:11:41 -05005002 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07005003 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
5004 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05005005 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08005006 }
5007
5008 // Create the return type that was a special structure
5009 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06005010 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08005011 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
5012 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
5013
5014 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
5015
5016 // Decode the return type
5017 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
5018 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07005019 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08005020 // Process image atomic operations
5021
5022 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5023 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005024 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005025 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005026 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005027
Jeff Bolz36831c92018-09-05 10:11:41 -05005028 spv::Id resultTypeId;
5029 // imageAtomicStore has a void return type so base the pointer type on
5030 // the type of the value operand.
5031 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005032 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005033 } else {
5034 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5035 }
John Kessenich56bab042015-09-16 10:54:31 -06005036 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005037 if (imageType.getQualifier().nonUniform) {
5038 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5039 }
Rex Xufc618912015-09-09 16:42:49 +08005040
5041 std::vector<spv::Id> operands;
5042 operands.push_back(pointer);
5043 for (; opIt != arguments.end(); ++opIt)
5044 operands.push_back(*opIt);
5045
John Kessenich8985fc92020-03-03 10:25:07 -07005046 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5047 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005048 }
5049 }
5050
John Kessenicha28f7a72019-08-06 07:00:58 -06005051#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005052 // Check for fragment mask functions other than queries
5053 if (cracked.fragMask) {
5054 assert(sampler.ms);
5055
5056 auto opIt = arguments.begin();
5057 std::vector<spv::Id> operands;
5058
amhagan05506bb2017-06-13 16:53:02 -04005059 operands.push_back(params.sampler);
5060 ++opIt;
5061
5062 if (sampler.isSubpass()) {
5063 // add on the (0,0) coordinate
5064 spv::Id zero = builder.makeIntConstant(0);
5065 std::vector<spv::Id> comps;
5066 comps.push_back(zero);
5067 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005068 operands.push_back(builder.makeCompositeConstant(
5069 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005070 }
5071
5072 for (; opIt != arguments.end(); ++opIt)
5073 operands.push_back(*opIt);
5074
5075 spv::Op fragMaskOp = spv::OpNop;
5076 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5077 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5078 else if (node->getOp() == glslang::EOpFragmentFetch)
5079 fragMaskOp = spv::OpFragmentFetchAMD;
5080
5081 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5082 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5083 return builder.createOp(fragMaskOp, resultType(), operands);
5084 }
5085#endif
5086
Rex Xufc618912015-09-09 16:42:49 +08005087 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005088 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005089 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005090 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005091
John Kessenichfc51d282015-08-19 13:34:18 -06005092 // check for bias argument
5093 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005094 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005095 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005096 if (cracked.gather)
5097 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005098
5099 if (f16ShadowCompare)
5100 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005101 if (cracked.offset)
5102 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005103 else if (cracked.offsets)
5104 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005105 if (cracked.grad)
5106 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005107 if (cracked.lodClamp)
5108 ++nonBiasArgCount;
5109 if (sparse)
5110 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005111 if (imageFootprint)
5112 //Following three extra arguments
5113 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5114 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005115 if ((int)arguments.size() > nonBiasArgCount)
5116 bias = true;
5117 }
5118
John Kessenicha28f7a72019-08-06 07:00:58 -06005119#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005120 if (cracked.gather) {
5121 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5122 if (bias || cracked.lod ||
5123 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5124 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005125 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005126 }
5127 }
5128#endif
5129
John Kessenichfc51d282015-08-19 13:34:18 -06005130 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005131
John Kessenichfc51d282015-08-19 13:34:18 -06005132 params.coords = arguments[1];
5133 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005134 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005135
5136 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005137 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005138 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005139 ++extraArgs;
5140 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005141 params.Dref = arguments[2];
5142 ++extraArgs;
5143 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005144 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005145 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005146 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005147 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005148 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005149 dRefComp = builder.getNumComponents(params.coords) - 1;
5150 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005151 params.Dref = builder.createCompositeExtract(params.coords,
5152 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005153 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005154
5155 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005156 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005157 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005158 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005159 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5160 !(glslangIntermediate->getStage() == EShLangCompute &&
5161 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005162 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5163 noImplicitLod = true;
5164 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005165
5166 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005167 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005168 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005169 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005170 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005171
5172 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005173 if (cracked.grad) {
5174 params.gradX = arguments[2 + extraArgs];
5175 params.gradY = arguments[3 + extraArgs];
5176 extraArgs += 2;
5177 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005178
5179 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005180 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005181 params.offset = arguments[2 + extraArgs];
5182 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005183 } else if (cracked.offsets) {
5184 params.offsets = arguments[2 + extraArgs];
5185 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005186 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005187
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005188#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005189 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005190 if (cracked.lodClamp) {
5191 params.lodClamp = arguments[2 + extraArgs];
5192 ++extraArgs;
5193 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005194 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005195 if (sparse) {
5196 params.texelOut = arguments[2 + extraArgs];
5197 ++extraArgs;
5198 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005199 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005200 if (cracked.gather && ! sampler.shadow) {
5201 // default component is 0, if missing, otherwise an argument
5202 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005203 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005204 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005205 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005206 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005207 }
Chao Chen3a137962018-09-19 11:41:27 -07005208 spv::Id resultStruct = spv::NoResult;
5209 if (imageFootprint) {
5210 //Following three extra arguments
5211 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5212 params.granularity = arguments[2 + extraArgs];
5213 params.coarse = arguments[3 + extraArgs];
5214 resultStruct = arguments[4 + extraArgs];
5215 extraArgs += 3;
5216 }
5217#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005218 // bias
5219 if (bias) {
5220 params.bias = arguments[2 + extraArgs];
5221 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005222 }
John Kessenichfc51d282015-08-19 13:34:18 -06005223
John Kessenicha28f7a72019-08-06 07:00:58 -06005224#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005225 if (imageFootprint) {
5226 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5227 builder.addCapability(spv::CapabilityImageFootprintNV);
5228
5229
5230 //resultStructType(OpenGL type) contains 5 elements:
5231 //struct gl_TextureFootprint2DNV {
5232 // uvec2 anchor;
5233 // uvec2 offset;
5234 // uvec2 mask;
5235 // uint lod;
5236 // uint granularity;
5237 //};
5238 //or
5239 //struct gl_TextureFootprint3DNV {
5240 // uvec3 anchor;
5241 // uvec3 offset;
5242 // uvec2 mask;
5243 // uint lod;
5244 // uint granularity;
5245 //};
5246 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5247 assert(builder.isStructType(resultStructType));
5248
5249 //resType (SPIR-V type) contains 6 elements:
5250 //Member 0 must be a Boolean type scalar(LOD),
5251 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5252 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5253 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5254 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5255 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5256 std::vector<spv::Id> members;
5257 members.push_back(resultType());
5258 for (int i = 0; i < 5; i++) {
5259 members.push_back(builder.getContainedTypeId(resultStructType, i));
5260 }
5261 spv::Id resType = builder.makeStructType(members, "ResType");
5262
5263 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005264 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5265 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005266
5267 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5268 for (int i = 0; i < 5; i++) {
5269 builder.clearAccessChain();
5270 builder.setAccessChainLValue(resultStruct);
5271
5272 //Accessing to a struct we created, no coherent flag is set
5273 spv::Builder::AccessChain::CoherentFlags flags;
5274 flags.clear();
5275
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005276 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005277 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005278 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005279 }
5280 return builder.createCompositeExtract(res, resultType(), 0);
5281 }
5282#endif
5283
John Kessenich65336482016-06-16 14:06:26 -06005284 // projective component (might not to move)
5285 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5286 // are divided by the last component of P."
5287 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5288 // unused components will appear after all used components."
5289 if (cracked.proj) {
5290 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5291 int projTargetComp;
5292 switch (sampler.dim) {
5293 case glslang::Esd1D: projTargetComp = 1; break;
5294 case glslang::Esd2D: projTargetComp = 2; break;
5295 case glslang::EsdRect: projTargetComp = 2; break;
5296 default: projTargetComp = projSourceComp; break;
5297 }
5298 // copy the projective coordinate if we have to
5299 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005300 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005301 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005302 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005303 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005304 }
5305 }
5306
John Kessenichf8d1d742019-10-21 06:55:11 -06005307#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005308 // nonprivate
5309 if (imageType.getQualifier().nonprivate) {
5310 params.nonprivate = true;
5311 }
5312
5313 // volatile
5314 if (imageType.getQualifier().volatil) {
5315 params.volatil = true;
5316 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005317#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005318
St0fFa1184dd2018-04-09 21:08:14 +02005319 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005320 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5321 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005322 );
LoopDawg4425f242018-02-18 11:40:01 -07005323
5324 if (components != node->getType().getVectorSize())
5325 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5326
5327 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005328}
5329
5330spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5331{
5332 // Grab the function's pointer from the previously created function
5333 spv::Function* function = functionMap[node->getName().c_str()];
5334 if (! function)
5335 return 0;
5336
5337 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5338 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5339
5340 // See comments in makeFunctions() for details about the semantics for parameter passing.
5341 //
5342 // These imply we need a four step process:
5343 // 1. Evaluate the arguments
5344 // 2. Allocate and make copies of in, out, and inout arguments
5345 // 3. Make the call
5346 // 4. Copy back the results
5347
John Kessenichd3ed90b2018-05-04 11:43:03 -06005348 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005349 std::vector<spv::Builder::AccessChain> lValues;
5350 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005351 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005352 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005353 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005354 // build l-value
5355 builder.clearAccessChain();
5356 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005357 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005358 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005359 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005360 // save l-value
5361 lValues.push_back(builder.getAccessChain());
5362 } else {
5363 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005364 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005365 }
5366 }
5367
5368 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5369 // copy the original into that space.
5370 //
5371 // Also, build up the list of actual arguments to pass in for the call
5372 int lValueCount = 0;
5373 int rValueCount = 0;
5374 std::vector<spv::Id> spvArgs;
5375 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5376 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005377 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005378 builder.setAccessChain(lValues[lValueCount]);
5379 arg = builder.accessChainGetLValue();
5380 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005381 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005382 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005383 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005384 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005385 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5386 // need to copy the input into output space
5387 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005388 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005389 builder.clearAccessChain();
5390 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005391 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005392 }
5393 ++lValueCount;
5394 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005395 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005396 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005397 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005398 {
John Kessenich435dd802020-06-30 01:27:08 -06005399 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005400 builder.clearAccessChain();
5401 builder.setAccessChainLValue(argCopy);
5402 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005403 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005404 } else
5405 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005406 ++rValueCount;
5407 }
5408 spvArgs.push_back(arg);
5409 }
5410
5411 // 3. Make the call.
5412 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005413 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005414
5415 // 4. Copy back out an "out" arguments.
5416 lValueCount = 0;
5417 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005418 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005419 ++lValueCount;
5420 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005421 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005422 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005423 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005424 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005425 }
5426 ++lValueCount;
5427 }
5428 }
5429
5430 return result;
5431}
5432
5433// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005434spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005435 spv::Id typeId, spv::Id left, spv::Id right,
5436 glslang::TBasicType typeProxy, bool reduceComparison)
5437{
John Kessenich66011cb2018-03-06 16:12:04 -07005438 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5439 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005440 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005441
5442 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005443 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005444 bool comparison = false;
5445
5446 switch (op) {
5447 case glslang::EOpAdd:
5448 case glslang::EOpAddAssign:
5449 if (isFloat)
5450 binOp = spv::OpFAdd;
5451 else
5452 binOp = spv::OpIAdd;
5453 break;
5454 case glslang::EOpSub:
5455 case glslang::EOpSubAssign:
5456 if (isFloat)
5457 binOp = spv::OpFSub;
5458 else
5459 binOp = spv::OpISub;
5460 break;
5461 case glslang::EOpMul:
5462 case glslang::EOpMulAssign:
5463 if (isFloat)
5464 binOp = spv::OpFMul;
5465 else
5466 binOp = spv::OpIMul;
5467 break;
5468 case glslang::EOpVectorTimesScalar:
5469 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005470 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005471 if (builder.isVector(right))
5472 std::swap(left, right);
5473 assert(builder.isScalar(right));
5474 needMatchingVectors = false;
5475 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005476 } else if (isFloat)
5477 binOp = spv::OpFMul;
5478 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005479 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005480 break;
5481 case glslang::EOpVectorTimesMatrix:
5482 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005483 binOp = spv::OpVectorTimesMatrix;
5484 break;
5485 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005486 binOp = spv::OpMatrixTimesVector;
5487 break;
5488 case glslang::EOpMatrixTimesScalar:
5489 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005490 binOp = spv::OpMatrixTimesScalar;
5491 break;
5492 case glslang::EOpMatrixTimesMatrix:
5493 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005494 binOp = spv::OpMatrixTimesMatrix;
5495 break;
5496 case glslang::EOpOuterProduct:
5497 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005498 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005499 break;
5500
5501 case glslang::EOpDiv:
5502 case glslang::EOpDivAssign:
5503 if (isFloat)
5504 binOp = spv::OpFDiv;
5505 else if (isUnsigned)
5506 binOp = spv::OpUDiv;
5507 else
5508 binOp = spv::OpSDiv;
5509 break;
5510 case glslang::EOpMod:
5511 case glslang::EOpModAssign:
5512 if (isFloat)
5513 binOp = spv::OpFMod;
5514 else if (isUnsigned)
5515 binOp = spv::OpUMod;
5516 else
5517 binOp = spv::OpSMod;
5518 break;
5519 case glslang::EOpRightShift:
5520 case glslang::EOpRightShiftAssign:
5521 if (isUnsigned)
5522 binOp = spv::OpShiftRightLogical;
5523 else
5524 binOp = spv::OpShiftRightArithmetic;
5525 break;
5526 case glslang::EOpLeftShift:
5527 case glslang::EOpLeftShiftAssign:
5528 binOp = spv::OpShiftLeftLogical;
5529 break;
5530 case glslang::EOpAnd:
5531 case glslang::EOpAndAssign:
5532 binOp = spv::OpBitwiseAnd;
5533 break;
5534 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005535 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005536 binOp = spv::OpLogicalAnd;
5537 break;
5538 case glslang::EOpInclusiveOr:
5539 case glslang::EOpInclusiveOrAssign:
5540 binOp = spv::OpBitwiseOr;
5541 break;
5542 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005543 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005544 binOp = spv::OpLogicalOr;
5545 break;
5546 case glslang::EOpExclusiveOr:
5547 case glslang::EOpExclusiveOrAssign:
5548 binOp = spv::OpBitwiseXor;
5549 break;
5550 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005551 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005552 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005553 break;
5554
Ian Romanickb3bd4022019-01-21 08:57:25 -08005555 case glslang::EOpAbsDifference:
5556 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5557 break;
5558
5559 case glslang::EOpAddSaturate:
5560 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5561 break;
5562
5563 case glslang::EOpSubSaturate:
5564 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5565 break;
5566
5567 case glslang::EOpAverage:
5568 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5569 break;
5570
5571 case glslang::EOpAverageRounded:
5572 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5573 break;
5574
5575 case glslang::EOpMul32x16:
5576 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5577 break;
5578
John Kessenich140f3df2015-06-26 16:58:36 -06005579 case glslang::EOpLessThan:
5580 case glslang::EOpGreaterThan:
5581 case glslang::EOpLessThanEqual:
5582 case glslang::EOpGreaterThanEqual:
5583 case glslang::EOpEqual:
5584 case glslang::EOpNotEqual:
5585 case glslang::EOpVectorEqual:
5586 case glslang::EOpVectorNotEqual:
5587 comparison = true;
5588 break;
5589 default:
5590 break;
5591 }
5592
John Kessenich7c1aa102015-10-15 13:29:11 -06005593 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005594 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005595 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005596 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5597 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005598 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005599
5600 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005601 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005602 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005603
qining25262b32016-05-06 17:25:16 -04005604 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005605 decorations.addNoContraction(builder, result);
5606 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005607 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005608 }
5609
5610 if (! comparison)
5611 return 0;
5612
John Kessenich7c1aa102015-10-15 13:29:11 -06005613 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005614
John Kessenich4583b612016-08-07 19:14:22 -06005615 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005616 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5617 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005618 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005619 return result;
5620 }
John Kessenich140f3df2015-06-26 16:58:36 -06005621
5622 switch (op) {
5623 case glslang::EOpLessThan:
5624 if (isFloat)
5625 binOp = spv::OpFOrdLessThan;
5626 else if (isUnsigned)
5627 binOp = spv::OpULessThan;
5628 else
5629 binOp = spv::OpSLessThan;
5630 break;
5631 case glslang::EOpGreaterThan:
5632 if (isFloat)
5633 binOp = spv::OpFOrdGreaterThan;
5634 else if (isUnsigned)
5635 binOp = spv::OpUGreaterThan;
5636 else
5637 binOp = spv::OpSGreaterThan;
5638 break;
5639 case glslang::EOpLessThanEqual:
5640 if (isFloat)
5641 binOp = spv::OpFOrdLessThanEqual;
5642 else if (isUnsigned)
5643 binOp = spv::OpULessThanEqual;
5644 else
5645 binOp = spv::OpSLessThanEqual;
5646 break;
5647 case glslang::EOpGreaterThanEqual:
5648 if (isFloat)
5649 binOp = spv::OpFOrdGreaterThanEqual;
5650 else if (isUnsigned)
5651 binOp = spv::OpUGreaterThanEqual;
5652 else
5653 binOp = spv::OpSGreaterThanEqual;
5654 break;
5655 case glslang::EOpEqual:
5656 case glslang::EOpVectorEqual:
5657 if (isFloat)
5658 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005659 else if (isBool)
5660 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005661 else
5662 binOp = spv::OpIEqual;
5663 break;
5664 case glslang::EOpNotEqual:
5665 case glslang::EOpVectorNotEqual:
5666 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005667 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005668 else if (isBool)
5669 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005670 else
5671 binOp = spv::OpINotEqual;
5672 break;
5673 default:
5674 break;
5675 }
5676
qining25262b32016-05-06 17:25:16 -04005677 if (binOp != spv::OpNop) {
5678 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005679 decorations.addNoContraction(builder, result);
5680 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005681 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005682 }
John Kessenich140f3df2015-06-26 16:58:36 -06005683
5684 return 0;
5685}
5686
John Kessenich04bb8a02015-12-12 12:28:14 -07005687//
5688// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5689// These can be any of:
5690//
5691// matrix * scalar
5692// scalar * matrix
5693// matrix * matrix linear algebraic
5694// matrix * vector
5695// vector * matrix
5696// matrix * matrix componentwise
5697// matrix op matrix op in {+, -, /}
5698// matrix op scalar op in {+, -, /}
5699// scalar op matrix op in {+, -, /}
5700//
John Kessenichead86222018-03-28 18:01:20 -06005701spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5702 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005703{
5704 bool firstClass = true;
5705
5706 // First, handle first-class matrix operations (* and matrix/scalar)
5707 switch (op) {
5708 case spv::OpFDiv:
5709 if (builder.isMatrix(left) && builder.isScalar(right)) {
5710 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005711 spv::Id resultType = builder.getTypeId(right);
5712 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005713 op = spv::OpMatrixTimesScalar;
5714 } else
5715 firstClass = false;
5716 break;
5717 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005718 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005719 std::swap(left, right);
5720 assert(builder.isScalar(right));
5721 break;
5722 case spv::OpVectorTimesMatrix:
5723 assert(builder.isVector(left));
5724 assert(builder.isMatrix(right));
5725 break;
5726 case spv::OpMatrixTimesVector:
5727 assert(builder.isMatrix(left));
5728 assert(builder.isVector(right));
5729 break;
5730 case spv::OpMatrixTimesMatrix:
5731 assert(builder.isMatrix(left));
5732 assert(builder.isMatrix(right));
5733 break;
5734 default:
5735 firstClass = false;
5736 break;
5737 }
5738
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005739 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5740 firstClass = true;
5741
qining25262b32016-05-06 17:25:16 -04005742 if (firstClass) {
5743 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005744 decorations.addNoContraction(builder, result);
5745 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005746 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005747 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005748
LoopDawg592860c2016-06-09 08:57:35 -06005749 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005750 // The result type of all of them is the same type as the (a) matrix operand.
5751 // The algorithm is to:
5752 // - break the matrix(es) into vectors
5753 // - smear any scalar to a vector
5754 // - do vector operations
5755 // - make a matrix out the vector results
5756 switch (op) {
5757 case spv::OpFAdd:
5758 case spv::OpFSub:
5759 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005760 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005761 case spv::OpFMul:
5762 {
5763 // one time set up...
5764 bool leftMat = builder.isMatrix(left);
5765 bool rightMat = builder.isMatrix(right);
5766 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5767 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5768 spv::Id scalarType = builder.getScalarTypeId(typeId);
5769 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5770 std::vector<spv::Id> results;
5771 spv::Id smearVec = spv::NoResult;
5772 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005773 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005774 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005775 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005776
5777 // do each vector op
5778 for (unsigned int c = 0; c < numCols; ++c) {
5779 std::vector<unsigned int> indexes;
5780 indexes.push_back(c);
5781 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5782 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005783 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005784 decorations.addNoContraction(builder, result);
5785 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005786 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005787 }
5788
5789 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005790 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005791 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005792 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005793 }
5794 default:
5795 assert(0);
5796 return spv::NoResult;
5797 }
5798}
5799
John Kessenichead86222018-03-28 18:01:20 -06005800spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005801 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005802{
5803 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005804 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005805 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005806 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5807 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005808
5809 switch (op) {
5810 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005811 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005812 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005813 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005814 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005815 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005816 unaryOp = spv::OpSNegate;
5817 break;
5818
5819 case glslang::EOpLogicalNot:
5820 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005821 unaryOp = spv::OpLogicalNot;
5822 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005823 case glslang::EOpBitwiseNot:
5824 unaryOp = spv::OpNot;
5825 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005826
John Kessenich140f3df2015-06-26 16:58:36 -06005827 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005828 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005829 break;
5830 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005831 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005832 break;
5833 case glslang::EOpTranspose:
5834 unaryOp = spv::OpTranspose;
5835 break;
5836
5837 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005838 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005839 break;
5840 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005841 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005842 break;
5843 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005844 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005847 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
5849 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005850 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005851 break;
5852 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005853 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005854 break;
5855 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005856 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005857 break;
5858 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005859 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005860 break;
5861
5862 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005863 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005864 break;
5865 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005866 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005867 break;
5868 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005869 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005870 break;
5871 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005872 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005873 break;
5874 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005875 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005876 break;
5877 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005878 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005879 break;
5880
5881 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005882 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005883 break;
5884 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005885 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005886 break;
5887
5888 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005889 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005890 break;
5891 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005892 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005893 break;
5894 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005895 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005896 break;
5897 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005898 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005899 break;
5900 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005901 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005902 break;
5903 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005904 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005905 break;
5906
5907 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005908 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005909 break;
5910 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005911 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005912 break;
5913 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005914 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005915 break;
5916 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005917 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005918 break;
5919 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005920 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005921 break;
5922 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005923 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005924 break;
5925
5926 case glslang::EOpIsNan:
5927 unaryOp = spv::OpIsNan;
5928 break;
5929 case glslang::EOpIsInf:
5930 unaryOp = spv::OpIsInf;
5931 break;
LoopDawg592860c2016-06-09 08:57:35 -06005932 case glslang::EOpIsFinite:
5933 unaryOp = spv::OpIsFinite;
5934 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005935
Rex Xucbc426e2015-12-15 16:03:10 +08005936 case glslang::EOpFloatBitsToInt:
5937 case glslang::EOpFloatBitsToUint:
5938 case glslang::EOpIntBitsToFloat:
5939 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005940 case glslang::EOpDoubleBitsToInt64:
5941 case glslang::EOpDoubleBitsToUint64:
5942 case glslang::EOpInt64BitsToDouble:
5943 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005944 case glslang::EOpFloat16BitsToInt16:
5945 case glslang::EOpFloat16BitsToUint16:
5946 case glslang::EOpInt16BitsToFloat16:
5947 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005948 unaryOp = spv::OpBitcast;
5949 break;
5950
John Kessenich140f3df2015-06-26 16:58:36 -06005951 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005952 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005953 break;
5954 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005955 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005956 break;
5957 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005958 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005959 break;
5960 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005961 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005962 break;
5963 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005964 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005965 break;
5966 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005967 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005968 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005969#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005970 case glslang::EOpPackSnorm4x8:
5971 libCall = spv::GLSLstd450PackSnorm4x8;
5972 break;
5973 case glslang::EOpUnpackSnorm4x8:
5974 libCall = spv::GLSLstd450UnpackSnorm4x8;
5975 break;
5976 case glslang::EOpPackUnorm4x8:
5977 libCall = spv::GLSLstd450PackUnorm4x8;
5978 break;
5979 case glslang::EOpUnpackUnorm4x8:
5980 libCall = spv::GLSLstd450UnpackUnorm4x8;
5981 break;
5982 case glslang::EOpPackDouble2x32:
5983 libCall = spv::GLSLstd450PackDouble2x32;
5984 break;
5985 case glslang::EOpUnpackDouble2x32:
5986 libCall = spv::GLSLstd450UnpackDouble2x32;
5987 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005988#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005989
Rex Xu8ff43de2016-04-22 16:51:45 +08005990 case glslang::EOpPackInt2x32:
5991 case glslang::EOpUnpackInt2x32:
5992 case glslang::EOpPackUint2x32:
5993 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005994 case glslang::EOpPack16:
5995 case glslang::EOpPack32:
5996 case glslang::EOpPack64:
5997 case glslang::EOpUnpack32:
5998 case glslang::EOpUnpack16:
5999 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08006000 case glslang::EOpPackInt2x16:
6001 case glslang::EOpUnpackInt2x16:
6002 case glslang::EOpPackUint2x16:
6003 case glslang::EOpUnpackUint2x16:
6004 case glslang::EOpPackInt4x16:
6005 case glslang::EOpUnpackInt4x16:
6006 case glslang::EOpPackUint4x16:
6007 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006008 case glslang::EOpPackFloat2x16:
6009 case glslang::EOpUnpackFloat2x16:
6010 unaryOp = spv::OpBitcast;
6011 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006012
John Kessenich140f3df2015-06-26 16:58:36 -06006013 case glslang::EOpDPdx:
6014 unaryOp = spv::OpDPdx;
6015 break;
6016 case glslang::EOpDPdy:
6017 unaryOp = spv::OpDPdy;
6018 break;
6019 case glslang::EOpFwidth:
6020 unaryOp = spv::OpFwidth;
6021 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006022
John Kessenich140f3df2015-06-26 16:58:36 -06006023 case glslang::EOpAny:
6024 unaryOp = spv::OpAny;
6025 break;
6026 case glslang::EOpAll:
6027 unaryOp = spv::OpAll;
6028 break;
6029
6030 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006031 if (isFloat)
6032 libCall = spv::GLSLstd450FAbs;
6033 else
6034 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006035 break;
6036 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006037 if (isFloat)
6038 libCall = spv::GLSLstd450FSign;
6039 else
6040 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006041 break;
6042
John Kessenicha28f7a72019-08-06 07:00:58 -06006043#ifndef GLSLANG_WEB
6044 case glslang::EOpDPdxFine:
6045 unaryOp = spv::OpDPdxFine;
6046 break;
6047 case glslang::EOpDPdyFine:
6048 unaryOp = spv::OpDPdyFine;
6049 break;
6050 case glslang::EOpFwidthFine:
6051 unaryOp = spv::OpFwidthFine;
6052 break;
6053 case glslang::EOpDPdxCoarse:
6054 unaryOp = spv::OpDPdxCoarse;
6055 break;
6056 case glslang::EOpDPdyCoarse:
6057 unaryOp = spv::OpDPdyCoarse;
6058 break;
6059 case glslang::EOpFwidthCoarse:
6060 unaryOp = spv::OpFwidthCoarse;
6061 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006062 case glslang::EOpRayQueryProceed:
6063 unaryOp = spv::OpRayQueryProceedKHR;
6064 break;
6065 case glslang::EOpRayQueryGetRayTMin:
6066 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6067 break;
6068 case glslang::EOpRayQueryGetRayFlags:
6069 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6070 break;
6071 case glslang::EOpRayQueryGetWorldRayOrigin:
6072 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6073 break;
6074 case glslang::EOpRayQueryGetWorldRayDirection:
6075 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6076 break;
6077 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6078 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6079 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006080 case glslang::EOpInterpolateAtCentroid:
6081 if (typeProxy == glslang::EbtFloat16)
6082 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6083 libCall = spv::GLSLstd450InterpolateAtCentroid;
6084 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006085 case glslang::EOpAtomicCounterIncrement:
6086 case glslang::EOpAtomicCounterDecrement:
6087 case glslang::EOpAtomicCounter:
6088 {
6089 // Handle all of the atomics in one place, in createAtomicOperation()
6090 std::vector<spv::Id> operands;
6091 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006092 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006093 }
6094
John Kessenichfc51d282015-08-19 13:34:18 -06006095 case glslang::EOpBitFieldReverse:
6096 unaryOp = spv::OpBitReverse;
6097 break;
6098 case glslang::EOpBitCount:
6099 unaryOp = spv::OpBitCount;
6100 break;
6101 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006102 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006103 break;
6104 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006105 if (isUnsigned)
6106 libCall = spv::GLSLstd450FindUMsb;
6107 else
6108 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006109 break;
6110
Ian Romanickb3bd4022019-01-21 08:57:25 -08006111 case glslang::EOpCountLeadingZeros:
6112 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6113 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6114 unaryOp = spv::OpUCountLeadingZerosINTEL;
6115 break;
6116
6117 case glslang::EOpCountTrailingZeros:
6118 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6119 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6120 unaryOp = spv::OpUCountTrailingZerosINTEL;
6121 break;
6122
Rex Xu574ab042016-04-14 16:53:07 +08006123 case glslang::EOpBallot:
6124 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006125 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006126 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006127 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006128 case glslang::EOpMinInvocations:
6129 case glslang::EOpMaxInvocations:
6130 case glslang::EOpAddInvocations:
6131 case glslang::EOpMinInvocationsNonUniform:
6132 case glslang::EOpMaxInvocationsNonUniform:
6133 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006134 case glslang::EOpMinInvocationsInclusiveScan:
6135 case glslang::EOpMaxInvocationsInclusiveScan:
6136 case glslang::EOpAddInvocationsInclusiveScan:
6137 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6138 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6139 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6140 case glslang::EOpMinInvocationsExclusiveScan:
6141 case glslang::EOpMaxInvocationsExclusiveScan:
6142 case glslang::EOpAddInvocationsExclusiveScan:
6143 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6144 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6145 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006146 {
6147 std::vector<spv::Id> operands;
6148 operands.push_back(operand);
6149 return createInvocationsOperation(op, typeId, operands, typeProxy);
6150 }
John Kessenich66011cb2018-03-06 16:12:04 -07006151 case glslang::EOpSubgroupAll:
6152 case glslang::EOpSubgroupAny:
6153 case glslang::EOpSubgroupAllEqual:
6154 case glslang::EOpSubgroupBroadcastFirst:
6155 case glslang::EOpSubgroupBallot:
6156 case glslang::EOpSubgroupInverseBallot:
6157 case glslang::EOpSubgroupBallotBitCount:
6158 case glslang::EOpSubgroupBallotInclusiveBitCount:
6159 case glslang::EOpSubgroupBallotExclusiveBitCount:
6160 case glslang::EOpSubgroupBallotFindLSB:
6161 case glslang::EOpSubgroupBallotFindMSB:
6162 case glslang::EOpSubgroupAdd:
6163 case glslang::EOpSubgroupMul:
6164 case glslang::EOpSubgroupMin:
6165 case glslang::EOpSubgroupMax:
6166 case glslang::EOpSubgroupAnd:
6167 case glslang::EOpSubgroupOr:
6168 case glslang::EOpSubgroupXor:
6169 case glslang::EOpSubgroupInclusiveAdd:
6170 case glslang::EOpSubgroupInclusiveMul:
6171 case glslang::EOpSubgroupInclusiveMin:
6172 case glslang::EOpSubgroupInclusiveMax:
6173 case glslang::EOpSubgroupInclusiveAnd:
6174 case glslang::EOpSubgroupInclusiveOr:
6175 case glslang::EOpSubgroupInclusiveXor:
6176 case glslang::EOpSubgroupExclusiveAdd:
6177 case glslang::EOpSubgroupExclusiveMul:
6178 case glslang::EOpSubgroupExclusiveMin:
6179 case glslang::EOpSubgroupExclusiveMax:
6180 case glslang::EOpSubgroupExclusiveAnd:
6181 case glslang::EOpSubgroupExclusiveOr:
6182 case glslang::EOpSubgroupExclusiveXor:
6183 case glslang::EOpSubgroupQuadSwapHorizontal:
6184 case glslang::EOpSubgroupQuadSwapVertical:
6185 case glslang::EOpSubgroupQuadSwapDiagonal: {
6186 std::vector<spv::Id> operands;
6187 operands.push_back(operand);
6188 return createSubgroupOperation(op, typeId, operands, typeProxy);
6189 }
Rex Xu9d93a232016-05-05 12:30:44 +08006190 case glslang::EOpMbcnt:
6191 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6192 libCall = spv::MbcntAMD;
6193 break;
6194
6195 case glslang::EOpCubeFaceIndex:
6196 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6197 libCall = spv::CubeFaceIndexAMD;
6198 break;
6199
6200 case glslang::EOpCubeFaceCoord:
6201 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6202 libCall = spv::CubeFaceCoordAMD;
6203 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006204 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006205 unaryOp = spv::OpGroupNonUniformPartitionNV;
6206 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006207 case glslang::EOpConstructReference:
6208 unaryOp = spv::OpBitcast;
6209 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006210#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006211
6212 case glslang::EOpCopyObject:
6213 unaryOp = spv::OpCopyObject;
6214 break;
6215
John Kessenich140f3df2015-06-26 16:58:36 -06006216 default:
6217 return 0;
6218 }
6219
6220 spv::Id id;
6221 if (libCall >= 0) {
6222 std::vector<spv::Id> args;
6223 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006224 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006225 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006226 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006227 }
John Kessenich140f3df2015-06-26 16:58:36 -06006228
John Kessenichb9197c82019-08-11 07:41:45 -06006229 decorations.addNoContraction(builder, id);
6230 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006231 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006232}
6233
John Kessenich7a53f762016-01-20 11:19:27 -07006234// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006235spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6236 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006237{
6238 // Handle unary operations vector by vector.
6239 // The result type is the same type as the original type.
6240 // The algorithm is to:
6241 // - break the matrix into vectors
6242 // - apply the operation to each vector
6243 // - make a matrix out the vector results
6244
6245 // get the types sorted out
6246 int numCols = builder.getNumColumns(operand);
6247 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006248 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6249 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006250 std::vector<spv::Id> results;
6251
6252 // do each vector op
6253 for (int c = 0; c < numCols; ++c) {
6254 std::vector<unsigned int> indexes;
6255 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006256 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6257 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006258 decorations.addNoContraction(builder, destVec);
6259 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006260 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006261 }
6262
6263 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006264 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006265 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006266 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006267}
6268
John Kessenichad7645f2018-06-04 19:11:25 -06006269// For converting integers where both the bitwidth and the signedness could
6270// change, but only do the width change here. The caller is still responsible
6271// for the signedness conversion.
6272spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006273{
John Kessenichad7645f2018-06-04 19:11:25 -06006274 // Get the result type width, based on the type to convert to.
6275 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006276 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006277 case glslang::EOpConvInt16ToUint8:
6278 case glslang::EOpConvIntToUint8:
6279 case glslang::EOpConvInt64ToUint8:
6280 case glslang::EOpConvUint16ToInt8:
6281 case glslang::EOpConvUintToInt8:
6282 case glslang::EOpConvUint64ToInt8:
6283 width = 8;
6284 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006285 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006286 case glslang::EOpConvIntToUint16:
6287 case glslang::EOpConvInt64ToUint16:
6288 case glslang::EOpConvUint8ToInt16:
6289 case glslang::EOpConvUintToInt16:
6290 case glslang::EOpConvUint64ToInt16:
6291 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006292 break;
6293 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006294 case glslang::EOpConvInt16ToUint:
6295 case glslang::EOpConvInt64ToUint:
6296 case glslang::EOpConvUint8ToInt:
6297 case glslang::EOpConvUint16ToInt:
6298 case glslang::EOpConvUint64ToInt:
6299 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006300 break;
6301 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006302 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006303 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006304 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006305 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006306 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006307 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006308 break;
6309
6310 default:
6311 assert(false && "Default missing");
6312 break;
6313 }
6314
John Kessenichad7645f2018-06-04 19:11:25 -06006315 // Get the conversion operation and result type,
6316 // based on the target width, but the source type.
6317 spv::Id type = spv::NoType;
6318 spv::Op convOp = spv::OpNop;
6319 switch(op) {
6320 case glslang::EOpConvInt8ToUint16:
6321 case glslang::EOpConvInt8ToUint:
6322 case glslang::EOpConvInt8ToUint64:
6323 case glslang::EOpConvInt16ToUint8:
6324 case glslang::EOpConvInt16ToUint:
6325 case glslang::EOpConvInt16ToUint64:
6326 case glslang::EOpConvIntToUint8:
6327 case glslang::EOpConvIntToUint16:
6328 case glslang::EOpConvIntToUint64:
6329 case glslang::EOpConvInt64ToUint8:
6330 case glslang::EOpConvInt64ToUint16:
6331 case glslang::EOpConvInt64ToUint:
6332 convOp = spv::OpSConvert;
6333 type = builder.makeIntType(width);
6334 break;
6335 default:
6336 convOp = spv::OpUConvert;
6337 type = builder.makeUintType(width);
6338 break;
6339 }
6340
John Kessenich66011cb2018-03-06 16:12:04 -07006341 if (vectorSize > 0)
6342 type = builder.makeVectorType(type, vectorSize);
6343
John Kessenichad7645f2018-06-04 19:11:25 -06006344 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006345}
6346
John Kessenichead86222018-03-28 18:01:20 -06006347spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6348 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006349{
6350 spv::Op convOp = spv::OpNop;
6351 spv::Id zero = 0;
6352 spv::Id one = 0;
6353
6354 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6355
6356 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006357 case glslang::EOpConvIntToBool:
6358 case glslang::EOpConvUintToBool:
6359 zero = builder.makeUintConstant(0);
6360 zero = makeSmearedConstant(zero, vectorSize);
6361 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006362 case glslang::EOpConvFloatToBool:
6363 zero = builder.makeFloatConstant(0.0F);
6364 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006365 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006366 case glslang::EOpConvBoolToFloat:
6367 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006368 zero = builder.makeFloatConstant(0.0F);
6369 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006370 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006371
John Kessenich140f3df2015-06-26 16:58:36 -06006372 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006373 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006374#ifndef GLSLANG_WEB
6375 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006376 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006377 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006378 } else
6379#endif
6380 {
6381 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006382 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006383 }
Rex Xucabbb782017-03-24 13:41:14 +08006384
John Kessenich140f3df2015-06-26 16:58:36 -06006385 convOp = spv::OpSelect;
6386 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006387
John Kessenich140f3df2015-06-26 16:58:36 -06006388 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006389 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006390#ifndef GLSLANG_WEB
6391 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006392 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006393 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006394 } else
6395#endif
6396 {
6397 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006398 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006399 }
Rex Xucabbb782017-03-24 13:41:14 +08006400
John Kessenich140f3df2015-06-26 16:58:36 -06006401 convOp = spv::OpSelect;
6402 break;
6403
John Kessenich66011cb2018-03-06 16:12:04 -07006404 case glslang::EOpConvInt8ToFloat16:
6405 case glslang::EOpConvInt8ToFloat:
6406 case glslang::EOpConvInt8ToDouble:
6407 case glslang::EOpConvInt16ToFloat16:
6408 case glslang::EOpConvInt16ToFloat:
6409 case glslang::EOpConvInt16ToDouble:
6410 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006411 case glslang::EOpConvIntToFloat:
6412 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006413 case glslang::EOpConvInt64ToFloat:
6414 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006415 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006416 convOp = spv::OpConvertSToF;
6417 break;
6418
John Kessenich66011cb2018-03-06 16:12:04 -07006419 case glslang::EOpConvUint8ToFloat16:
6420 case glslang::EOpConvUint8ToFloat:
6421 case glslang::EOpConvUint8ToDouble:
6422 case glslang::EOpConvUint16ToFloat16:
6423 case glslang::EOpConvUint16ToFloat:
6424 case glslang::EOpConvUint16ToDouble:
6425 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006426 case glslang::EOpConvUintToFloat:
6427 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006428 case glslang::EOpConvUint64ToFloat:
6429 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006430 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006431 convOp = spv::OpConvertUToF;
6432 break;
6433
John Kessenich66011cb2018-03-06 16:12:04 -07006434 case glslang::EOpConvFloat16ToInt8:
6435 case glslang::EOpConvFloatToInt8:
6436 case glslang::EOpConvDoubleToInt8:
6437 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006438 case glslang::EOpConvFloatToInt16:
6439 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006440 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006441 case glslang::EOpConvFloatToInt:
6442 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006443 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006444 case glslang::EOpConvFloatToInt64:
6445 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006446 convOp = spv::OpConvertFToS;
6447 break;
6448
John Kessenich66011cb2018-03-06 16:12:04 -07006449 case glslang::EOpConvUint8ToInt8:
6450 case glslang::EOpConvInt8ToUint8:
6451 case glslang::EOpConvUint16ToInt16:
6452 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006453 case glslang::EOpConvUintToInt:
6454 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006455 case glslang::EOpConvUint64ToInt64:
6456 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006457 if (builder.isInSpecConstCodeGenMode()) {
6458 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006459#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006460 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6461 zero = builder.makeUint8Constant(0);
6462 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006463 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006464 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6465 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006466 } else
6467#endif
6468 {
Rex Xucabbb782017-03-24 13:41:14 +08006469 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006470 }
qining189b2032016-04-12 23:16:20 -04006471 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006472 // Use OpIAdd, instead of OpBitcast to do the conversion when
6473 // generating for OpSpecConstantOp instruction.
6474 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6475 }
6476 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006477 convOp = spv::OpBitcast;
6478 break;
6479
John Kessenich66011cb2018-03-06 16:12:04 -07006480 case glslang::EOpConvFloat16ToUint8:
6481 case glslang::EOpConvFloatToUint8:
6482 case glslang::EOpConvDoubleToUint8:
6483 case glslang::EOpConvFloat16ToUint16:
6484 case glslang::EOpConvFloatToUint16:
6485 case glslang::EOpConvDoubleToUint16:
6486 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006487 case glslang::EOpConvFloatToUint:
6488 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006489 case glslang::EOpConvFloatToUint64:
6490 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006491 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006492 convOp = spv::OpConvertFToU;
6493 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006494
John Kessenich39697cd2019-08-08 10:35:51 -06006495#ifndef GLSLANG_WEB
6496 case glslang::EOpConvInt8ToBool:
6497 case glslang::EOpConvUint8ToBool:
6498 zero = builder.makeUint8Constant(0);
6499 zero = makeSmearedConstant(zero, vectorSize);
6500 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6501 case glslang::EOpConvInt16ToBool:
6502 case glslang::EOpConvUint16ToBool:
6503 zero = builder.makeUint16Constant(0);
6504 zero = makeSmearedConstant(zero, vectorSize);
6505 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6506 case glslang::EOpConvInt64ToBool:
6507 case glslang::EOpConvUint64ToBool:
6508 zero = builder.makeUint64Constant(0);
6509 zero = makeSmearedConstant(zero, vectorSize);
6510 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6511 case glslang::EOpConvDoubleToBool:
6512 zero = builder.makeDoubleConstant(0.0);
6513 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006514 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006515 case glslang::EOpConvFloat16ToBool:
6516 zero = builder.makeFloat16Constant(0.0F);
6517 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006518 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006519 case glslang::EOpConvBoolToDouble:
6520 convOp = spv::OpSelect;
6521 zero = builder.makeDoubleConstant(0.0);
6522 one = builder.makeDoubleConstant(1.0);
6523 break;
6524 case glslang::EOpConvBoolToFloat16:
6525 convOp = spv::OpSelect;
6526 zero = builder.makeFloat16Constant(0.0F);
6527 one = builder.makeFloat16Constant(1.0F);
6528 break;
6529 case glslang::EOpConvBoolToInt8:
6530 zero = builder.makeInt8Constant(0);
6531 one = builder.makeInt8Constant(1);
6532 convOp = spv::OpSelect;
6533 break;
6534 case glslang::EOpConvBoolToUint8:
6535 zero = builder.makeUint8Constant(0);
6536 one = builder.makeUint8Constant(1);
6537 convOp = spv::OpSelect;
6538 break;
6539 case glslang::EOpConvBoolToInt16:
6540 zero = builder.makeInt16Constant(0);
6541 one = builder.makeInt16Constant(1);
6542 convOp = spv::OpSelect;
6543 break;
6544 case glslang::EOpConvBoolToUint16:
6545 zero = builder.makeUint16Constant(0);
6546 one = builder.makeUint16Constant(1);
6547 convOp = spv::OpSelect;
6548 break;
6549 case glslang::EOpConvDoubleToFloat:
6550 case glslang::EOpConvFloatToDouble:
6551 case glslang::EOpConvDoubleToFloat16:
6552 case glslang::EOpConvFloat16ToDouble:
6553 case glslang::EOpConvFloatToFloat16:
6554 case glslang::EOpConvFloat16ToFloat:
6555 convOp = spv::OpFConvert;
6556 if (builder.isMatrixType(destType))
6557 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6558 break;
6559
John Kessenich66011cb2018-03-06 16:12:04 -07006560 case glslang::EOpConvInt8ToInt16:
6561 case glslang::EOpConvInt8ToInt:
6562 case glslang::EOpConvInt8ToInt64:
6563 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006564 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006565 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006566 case glslang::EOpConvIntToInt8:
6567 case glslang::EOpConvIntToInt16:
6568 case glslang::EOpConvIntToInt64:
6569 case glslang::EOpConvInt64ToInt8:
6570 case glslang::EOpConvInt64ToInt16:
6571 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006572 convOp = spv::OpSConvert;
6573 break;
6574
John Kessenich66011cb2018-03-06 16:12:04 -07006575 case glslang::EOpConvUint8ToUint16:
6576 case glslang::EOpConvUint8ToUint:
6577 case glslang::EOpConvUint8ToUint64:
6578 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006579 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006580 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006581 case glslang::EOpConvUintToUint8:
6582 case glslang::EOpConvUintToUint16:
6583 case glslang::EOpConvUintToUint64:
6584 case glslang::EOpConvUint64ToUint8:
6585 case glslang::EOpConvUint64ToUint16:
6586 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006587 convOp = spv::OpUConvert;
6588 break;
6589
John Kessenich66011cb2018-03-06 16:12:04 -07006590 case glslang::EOpConvInt8ToUint16:
6591 case glslang::EOpConvInt8ToUint:
6592 case glslang::EOpConvInt8ToUint64:
6593 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006594 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006595 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006596 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006597 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006598 case glslang::EOpConvIntToUint64:
6599 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006600 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006601 case glslang::EOpConvInt64ToUint:
6602 case glslang::EOpConvUint8ToInt16:
6603 case glslang::EOpConvUint8ToInt:
6604 case glslang::EOpConvUint8ToInt64:
6605 case glslang::EOpConvUint16ToInt8:
6606 case glslang::EOpConvUint16ToInt:
6607 case glslang::EOpConvUint16ToInt64:
6608 case glslang::EOpConvUintToInt8:
6609 case glslang::EOpConvUintToInt16:
6610 case glslang::EOpConvUintToInt64:
6611 case glslang::EOpConvUint64ToInt8:
6612 case glslang::EOpConvUint64ToInt16:
6613 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006614 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006615 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006616
6617 if (builder.isInSpecConstCodeGenMode()) {
6618 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006619 switch(op) {
6620 case glslang::EOpConvInt16ToUint8:
6621 case glslang::EOpConvIntToUint8:
6622 case glslang::EOpConvInt64ToUint8:
6623 case glslang::EOpConvUint16ToInt8:
6624 case glslang::EOpConvUintToInt8:
6625 case glslang::EOpConvUint64ToInt8:
6626 zero = builder.makeUint8Constant(0);
6627 break;
6628 case glslang::EOpConvInt8ToUint16:
6629 case glslang::EOpConvIntToUint16:
6630 case glslang::EOpConvInt64ToUint16:
6631 case glslang::EOpConvUint8ToInt16:
6632 case glslang::EOpConvUintToInt16:
6633 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006634 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006635 break;
6636 case glslang::EOpConvInt8ToUint:
6637 case glslang::EOpConvInt16ToUint:
6638 case glslang::EOpConvInt64ToUint:
6639 case glslang::EOpConvUint8ToInt:
6640 case glslang::EOpConvUint16ToInt:
6641 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006642 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006643 break;
6644 case glslang::EOpConvInt8ToUint64:
6645 case glslang::EOpConvInt16ToUint64:
6646 case glslang::EOpConvIntToUint64:
6647 case glslang::EOpConvUint8ToInt64:
6648 case glslang::EOpConvUint16ToInt64:
6649 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006650 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006651 break;
6652 default:
6653 assert(false && "Default missing");
6654 break;
6655 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006656 zero = makeSmearedConstant(zero, vectorSize);
6657 // Use OpIAdd, instead of OpBitcast to do the conversion when
6658 // generating for OpSpecConstantOp instruction.
6659 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6660 }
6661 // For normal run-time conversion instruction, use OpBitcast.
6662 convOp = spv::OpBitcast;
6663 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006664 case glslang::EOpConvUint64ToPtr:
6665 convOp = spv::OpConvertUToPtr;
6666 break;
6667 case glslang::EOpConvPtrToUint64:
6668 convOp = spv::OpConvertPtrToU;
6669 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006670 case glslang::EOpConvPtrToUvec2:
6671 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006672 if (builder.isVector(operand))
6673 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6674 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006675 convOp = spv::OpBitcast;
6676 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006677#endif
6678
John Kessenich140f3df2015-06-26 16:58:36 -06006679 default:
6680 break;
6681 }
6682
6683 spv::Id result = 0;
6684 if (convOp == spv::OpNop)
6685 return result;
6686
6687 if (convOp == spv::OpSelect) {
6688 zero = makeSmearedConstant(zero, vectorSize);
6689 one = makeSmearedConstant(one, vectorSize);
6690 result = builder.createTriOp(convOp, destType, operand, one, zero);
6691 } else
6692 result = builder.createUnaryOp(convOp, destType, operand);
6693
John Kessenichead86222018-03-28 18:01:20 -06006694 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006695 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006696 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006697}
6698
6699spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6700{
6701 if (vectorSize == 0)
6702 return constant;
6703
6704 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6705 std::vector<spv::Id> components;
6706 for (int c = 0; c < vectorSize; ++c)
6707 components.push_back(constant);
6708 return builder.makeCompositeConstant(vectorTypeId, components);
6709}
6710
John Kessenich426394d2015-07-23 10:22:48 -06006711// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006712spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6713 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6714 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006715{
6716 spv::Op opCode = spv::OpNop;
6717
6718 switch (op) {
6719 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006720 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006721 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006722 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006723 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6724 opCode = spv::OpAtomicFAddEXT;
6725 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6726 if (typeProxy == glslang::EbtFloat)
6727 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6728 else
6729 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6730 }
John Kessenich426394d2015-07-23 10:22:48 -06006731 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006732 case glslang::EOpAtomicCounterSubtract:
6733 opCode = spv::OpAtomicISub;
6734 break;
John Kessenich426394d2015-07-23 10:22:48 -06006735 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006736 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006737 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006738 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6739 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006740 break;
6741 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006742 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006743 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006744 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6745 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006746 break;
6747 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006748 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006749 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006750 opCode = spv::OpAtomicAnd;
6751 break;
6752 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006753 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006754 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006755 opCode = spv::OpAtomicOr;
6756 break;
6757 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006758 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006759 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006760 opCode = spv::OpAtomicXor;
6761 break;
6762 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006763 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006764 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006765 opCode = spv::OpAtomicExchange;
6766 break;
6767 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006768 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006769 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006770 opCode = spv::OpAtomicCompareExchange;
6771 break;
6772 case glslang::EOpAtomicCounterIncrement:
6773 opCode = spv::OpAtomicIIncrement;
6774 break;
6775 case glslang::EOpAtomicCounterDecrement:
6776 opCode = spv::OpAtomicIDecrement;
6777 break;
6778 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006779 case glslang::EOpImageAtomicLoad:
6780 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006781 opCode = spv::OpAtomicLoad;
6782 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006783 case glslang::EOpAtomicStore:
6784 case glslang::EOpImageAtomicStore:
6785 opCode = spv::OpAtomicStore;
6786 break;
John Kessenich426394d2015-07-23 10:22:48 -06006787 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006788 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006789 break;
6790 }
6791
Rex Xue8fe8b02017-09-26 15:42:56 +08006792 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6793 builder.addCapability(spv::CapabilityInt64Atomics);
6794
John Kessenich426394d2015-07-23 10:22:48 -06006795 // Sort out the operands
6796 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006797 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006798 // - compare-exchange swaps the value and comparator
6799 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006800 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006801 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6802 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6803 spv::Id scopeId;
6804 if (glslangIntermediate->usingVulkanMemoryModel()) {
6805 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6806 } else {
6807 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6808 }
6809 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006810 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6811 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006812 spv::MemorySemanticsVolatileMask :
6813 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006814 spv::Id semanticsId2 = semanticsId;
6815
6816 pointerId = operands[0];
6817 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6818 // no additional operands
6819 } else if (opCode == spv::OpAtomicCompareExchange) {
6820 compareId = operands[1];
6821 valueId = operands[2];
6822 if (operands.size() > 3) {
6823 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006824 semanticsId = builder.makeUintConstant(
6825 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6826 semanticsId2 = builder.makeUintConstant(
6827 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006828 }
6829 } else if (opCode == spv::OpAtomicLoad) {
6830 if (operands.size() > 1) {
6831 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006832 semanticsId = builder.makeUintConstant(
6833 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006834 }
6835 } else {
6836 // atomic store or RMW
6837 valueId = operands[1];
6838 if (operands.size() > 2) {
6839 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006840 semanticsId = builder.makeUintConstant
6841 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006842 }
Rex Xu04db3f52015-09-16 11:44:02 +08006843 }
John Kessenich426394d2015-07-23 10:22:48 -06006844
Jeff Bolz36831c92018-09-05 10:11:41 -05006845 // Check for capabilities
6846 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006847 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6848 spv::MemorySemanticsMakeVisibleKHRMask |
6849 spv::MemorySemanticsOutputMemoryKHRMask |
6850 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006851 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6852 }
John Kessenich426394d2015-07-23 10:22:48 -06006853
Jeff Bolz36831c92018-09-05 10:11:41 -05006854 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6855 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6856 }
John Kessenich48d6e792017-10-06 21:21:48 -06006857
Jeff Bolz36831c92018-09-05 10:11:41 -05006858 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6859 spvAtomicOperands.push_back(pointerId);
6860 spvAtomicOperands.push_back(scopeId);
6861 spvAtomicOperands.push_back(semanticsId);
6862 if (opCode == spv::OpAtomicCompareExchange) {
6863 spvAtomicOperands.push_back(semanticsId2);
6864 spvAtomicOperands.push_back(valueId);
6865 spvAtomicOperands.push_back(compareId);
6866 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6867 spvAtomicOperands.push_back(valueId);
6868 }
John Kessenich48d6e792017-10-06 21:21:48 -06006869
Jeff Bolz36831c92018-09-05 10:11:41 -05006870 if (opCode == spv::OpAtomicStore) {
6871 builder.createNoResultOp(opCode, spvAtomicOperands);
6872 return 0;
6873 } else {
6874 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6875
6876 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6877 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6878 if (op == glslang::EOpAtomicCounterDecrement)
6879 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6880
6881 return resultId;
6882 }
John Kessenich426394d2015-07-23 10:22:48 -06006883}
6884
John Kessenich91cef522016-05-05 16:45:40 -06006885// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006886spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6887 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006888{
John Kessenich66011cb2018-03-06 16:12:04 -07006889 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6890 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006891
Rex Xu51596642016-09-21 18:56:12 +08006892 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006893 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006894 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6895
chaocf200da82016-12-20 12:44:35 -08006896 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6897 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006898 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6899 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006900 } else if (op == glslang::EOpAnyInvocation ||
6901 op == glslang::EOpAllInvocations ||
6902 op == glslang::EOpAllInvocationsEqual) {
6903 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6904 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006905 } else {
6906 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006907 if (op == glslang::EOpMinInvocationsNonUniform ||
6908 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006909 op == glslang::EOpAddInvocationsNonUniform ||
6910 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6911 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6912 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6913 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6914 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6915 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006916 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006917
Rex Xu430ef402016-10-14 17:22:23 +08006918 switch (op) {
6919 case glslang::EOpMinInvocations:
6920 case glslang::EOpMaxInvocations:
6921 case glslang::EOpAddInvocations:
6922 case glslang::EOpMinInvocationsNonUniform:
6923 case glslang::EOpMaxInvocationsNonUniform:
6924 case glslang::EOpAddInvocationsNonUniform:
6925 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006926 break;
6927 case glslang::EOpMinInvocationsInclusiveScan:
6928 case glslang::EOpMaxInvocationsInclusiveScan:
6929 case glslang::EOpAddInvocationsInclusiveScan:
6930 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6931 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6932 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6933 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006934 break;
6935 case glslang::EOpMinInvocationsExclusiveScan:
6936 case glslang::EOpMaxInvocationsExclusiveScan:
6937 case glslang::EOpAddInvocationsExclusiveScan:
6938 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6939 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6940 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6941 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006942 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006943 default:
6944 break;
Rex Xu430ef402016-10-14 17:22:23 +08006945 }
John Kessenich149afc32018-08-14 13:31:43 -06006946 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6947 spvGroupOperands.push_back(scope);
6948 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006949 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006950 spvGroupOperands.push_back(groupOp);
6951 }
Rex Xu51596642016-09-21 18:56:12 +08006952 }
6953
John Kessenich149afc32018-08-14 13:31:43 -06006954 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6955 spv::IdImmediate op = { true, *opIt };
6956 spvGroupOperands.push_back(op);
6957 }
John Kessenich91cef522016-05-05 16:45:40 -06006958
6959 switch (op) {
6960 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006961 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006962 break;
John Kessenich91cef522016-05-05 16:45:40 -06006963 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006964 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006965 break;
John Kessenich91cef522016-05-05 16:45:40 -06006966 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006967 opCode = spv::OpSubgroupAllEqualKHR;
6968 break;
Rex Xu51596642016-09-21 18:56:12 +08006969 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006970 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006971 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006972 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006973 break;
6974 case glslang::EOpReadFirstInvocation:
6975 opCode = spv::OpSubgroupFirstInvocationKHR;
6976 break;
6977 case glslang::EOpBallot:
6978 {
6979 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6980 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6981 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6982 //
6983 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6984 //
6985 spv::Id uintType = builder.makeUintType(32);
6986 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6987 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6988
6989 std::vector<spv::Id> components;
6990 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6991 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6992
6993 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6994 return builder.createUnaryOp(spv::OpBitcast, typeId,
6995 builder.createCompositeConstruct(uvec2Type, components));
6996 }
6997
Rex Xu9d93a232016-05-05 12:30:44 +08006998 case glslang::EOpMinInvocations:
6999 case glslang::EOpMaxInvocations:
7000 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08007001 case glslang::EOpMinInvocationsInclusiveScan:
7002 case glslang::EOpMaxInvocationsInclusiveScan:
7003 case glslang::EOpAddInvocationsInclusiveScan:
7004 case glslang::EOpMinInvocationsExclusiveScan:
7005 case glslang::EOpMaxInvocationsExclusiveScan:
7006 case glslang::EOpAddInvocationsExclusiveScan:
7007 if (op == glslang::EOpMinInvocations ||
7008 op == glslang::EOpMinInvocationsInclusiveScan ||
7009 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007010 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007011 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007012 else {
7013 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007014 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007015 else
Rex Xu51596642016-09-21 18:56:12 +08007016 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007017 }
Rex Xu430ef402016-10-14 17:22:23 +08007018 } else if (op == glslang::EOpMaxInvocations ||
7019 op == glslang::EOpMaxInvocationsInclusiveScan ||
7020 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007021 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007022 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007023 else {
7024 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007025 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007026 else
Rex Xu51596642016-09-21 18:56:12 +08007027 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007028 }
7029 } else {
7030 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007031 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007032 else
Rex Xu51596642016-09-21 18:56:12 +08007033 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007034 }
7035
Rex Xu2bbbe062016-08-23 15:41:05 +08007036 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007037 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007038
7039 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007040 case glslang::EOpMinInvocationsNonUniform:
7041 case glslang::EOpMaxInvocationsNonUniform:
7042 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007043 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7044 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7045 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7046 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7047 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7048 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7049 if (op == glslang::EOpMinInvocationsNonUniform ||
7050 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7051 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007052 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007053 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007054 else {
7055 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007056 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007057 else
Rex Xu51596642016-09-21 18:56:12 +08007058 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007059 }
7060 }
Rex Xu430ef402016-10-14 17:22:23 +08007061 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7062 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7063 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007064 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007065 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007066 else {
7067 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007068 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007069 else
Rex Xu51596642016-09-21 18:56:12 +08007070 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007071 }
7072 }
7073 else {
7074 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007075 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007076 else
Rex Xu51596642016-09-21 18:56:12 +08007077 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007078 }
7079
Rex Xu2bbbe062016-08-23 15:41:05 +08007080 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007081 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007082
7083 break;
John Kessenich91cef522016-05-05 16:45:40 -06007084 default:
7085 logger->missingFunctionality("invocation operation");
7086 return spv::NoResult;
7087 }
Rex Xu51596642016-09-21 18:56:12 +08007088
7089 assert(opCode != spv::OpNop);
7090 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007091}
7092
Rex Xu2bbbe062016-08-23 15:41:05 +08007093// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007094spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7095 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007096{
7097 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7098 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007099 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007100 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007101 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7102 op == spv::OpGroupSMinNonUniformAMD ||
7103 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7104 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007105 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7106
7107 // Handle group invocation operations scalar by scalar.
7108 // The result type is the same type as the original type.
7109 // The algorithm is to:
7110 // - break the vector into scalars
7111 // - apply the operation to each scalar
7112 // - make a vector out the scalar results
7113
7114 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007115 int numComponents = builder.getNumComponents(operands[0]);
7116 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007117 std::vector<spv::Id> results;
7118
7119 // do each scalar op
7120 for (int comp = 0; comp < numComponents; ++comp) {
7121 std::vector<unsigned int> indexes;
7122 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007123 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7124 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007125 if (op == spv::OpSubgroupReadInvocationKHR) {
7126 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007127 spv::IdImmediate operand = { true, operands[1] };
7128 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007129 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007130 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7131 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007132 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007133 spv::IdImmediate operand = { true, operands[1] };
7134 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007135 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007136 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7137 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007138 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007139 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007140 spvGroupOperands.push_back(scalar);
7141 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007142
Rex Xub7072052016-09-26 15:53:40 +08007143 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007144 }
7145
7146 // put the pieces together
7147 return builder.createCompositeConstruct(typeId, results);
7148}
Rex Xu2bbbe062016-08-23 15:41:05 +08007149
John Kessenich66011cb2018-03-06 16:12:04 -07007150// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007151spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7152 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007153{
7154 // Add the required capabilities.
7155 switch (op) {
7156 case glslang::EOpSubgroupElect:
7157 builder.addCapability(spv::CapabilityGroupNonUniform);
7158 break;
7159 case glslang::EOpSubgroupAll:
7160 case glslang::EOpSubgroupAny:
7161 case glslang::EOpSubgroupAllEqual:
7162 builder.addCapability(spv::CapabilityGroupNonUniform);
7163 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7164 break;
7165 case glslang::EOpSubgroupBroadcast:
7166 case glslang::EOpSubgroupBroadcastFirst:
7167 case glslang::EOpSubgroupBallot:
7168 case glslang::EOpSubgroupInverseBallot:
7169 case glslang::EOpSubgroupBallotBitExtract:
7170 case glslang::EOpSubgroupBallotBitCount:
7171 case glslang::EOpSubgroupBallotInclusiveBitCount:
7172 case glslang::EOpSubgroupBallotExclusiveBitCount:
7173 case glslang::EOpSubgroupBallotFindLSB:
7174 case glslang::EOpSubgroupBallotFindMSB:
7175 builder.addCapability(spv::CapabilityGroupNonUniform);
7176 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7177 break;
7178 case glslang::EOpSubgroupShuffle:
7179 case glslang::EOpSubgroupShuffleXor:
7180 builder.addCapability(spv::CapabilityGroupNonUniform);
7181 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7182 break;
7183 case glslang::EOpSubgroupShuffleUp:
7184 case glslang::EOpSubgroupShuffleDown:
7185 builder.addCapability(spv::CapabilityGroupNonUniform);
7186 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7187 break;
7188 case glslang::EOpSubgroupAdd:
7189 case glslang::EOpSubgroupMul:
7190 case glslang::EOpSubgroupMin:
7191 case glslang::EOpSubgroupMax:
7192 case glslang::EOpSubgroupAnd:
7193 case glslang::EOpSubgroupOr:
7194 case glslang::EOpSubgroupXor:
7195 case glslang::EOpSubgroupInclusiveAdd:
7196 case glslang::EOpSubgroupInclusiveMul:
7197 case glslang::EOpSubgroupInclusiveMin:
7198 case glslang::EOpSubgroupInclusiveMax:
7199 case glslang::EOpSubgroupInclusiveAnd:
7200 case glslang::EOpSubgroupInclusiveOr:
7201 case glslang::EOpSubgroupInclusiveXor:
7202 case glslang::EOpSubgroupExclusiveAdd:
7203 case glslang::EOpSubgroupExclusiveMul:
7204 case glslang::EOpSubgroupExclusiveMin:
7205 case glslang::EOpSubgroupExclusiveMax:
7206 case glslang::EOpSubgroupExclusiveAnd:
7207 case glslang::EOpSubgroupExclusiveOr:
7208 case glslang::EOpSubgroupExclusiveXor:
7209 builder.addCapability(spv::CapabilityGroupNonUniform);
7210 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7211 break;
7212 case glslang::EOpSubgroupClusteredAdd:
7213 case glslang::EOpSubgroupClusteredMul:
7214 case glslang::EOpSubgroupClusteredMin:
7215 case glslang::EOpSubgroupClusteredMax:
7216 case glslang::EOpSubgroupClusteredAnd:
7217 case glslang::EOpSubgroupClusteredOr:
7218 case glslang::EOpSubgroupClusteredXor:
7219 builder.addCapability(spv::CapabilityGroupNonUniform);
7220 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7221 break;
7222 case glslang::EOpSubgroupQuadBroadcast:
7223 case glslang::EOpSubgroupQuadSwapHorizontal:
7224 case glslang::EOpSubgroupQuadSwapVertical:
7225 case glslang::EOpSubgroupQuadSwapDiagonal:
7226 builder.addCapability(spv::CapabilityGroupNonUniform);
7227 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7228 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007229 case glslang::EOpSubgroupPartitionedAdd:
7230 case glslang::EOpSubgroupPartitionedMul:
7231 case glslang::EOpSubgroupPartitionedMin:
7232 case glslang::EOpSubgroupPartitionedMax:
7233 case glslang::EOpSubgroupPartitionedAnd:
7234 case glslang::EOpSubgroupPartitionedOr:
7235 case glslang::EOpSubgroupPartitionedXor:
7236 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7237 case glslang::EOpSubgroupPartitionedInclusiveMul:
7238 case glslang::EOpSubgroupPartitionedInclusiveMin:
7239 case glslang::EOpSubgroupPartitionedInclusiveMax:
7240 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7241 case glslang::EOpSubgroupPartitionedInclusiveOr:
7242 case glslang::EOpSubgroupPartitionedInclusiveXor:
7243 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7244 case glslang::EOpSubgroupPartitionedExclusiveMul:
7245 case glslang::EOpSubgroupPartitionedExclusiveMin:
7246 case glslang::EOpSubgroupPartitionedExclusiveMax:
7247 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7248 case glslang::EOpSubgroupPartitionedExclusiveOr:
7249 case glslang::EOpSubgroupPartitionedExclusiveXor:
7250 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7251 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7252 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007253 default: assert(0 && "Unhandled subgroup operation!");
7254 }
7255
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007256
7257 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7258 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007259 const bool isBool = typeProxy == glslang::EbtBool;
7260
7261 spv::Op opCode = spv::OpNop;
7262
7263 // Figure out which opcode to use.
7264 switch (op) {
7265 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7266 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7267 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7268 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7269 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7270 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7271 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7272 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7273 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7274 case glslang::EOpSubgroupBallotBitCount:
7275 case glslang::EOpSubgroupBallotInclusiveBitCount:
7276 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7277 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7278 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7279 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7280 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7281 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7282 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7283 case glslang::EOpSubgroupAdd:
7284 case glslang::EOpSubgroupInclusiveAdd:
7285 case glslang::EOpSubgroupExclusiveAdd:
7286 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007287 case glslang::EOpSubgroupPartitionedAdd:
7288 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7289 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007290 if (isFloat) {
7291 opCode = spv::OpGroupNonUniformFAdd;
7292 } else {
7293 opCode = spv::OpGroupNonUniformIAdd;
7294 }
7295 break;
7296 case glslang::EOpSubgroupMul:
7297 case glslang::EOpSubgroupInclusiveMul:
7298 case glslang::EOpSubgroupExclusiveMul:
7299 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007300 case glslang::EOpSubgroupPartitionedMul:
7301 case glslang::EOpSubgroupPartitionedInclusiveMul:
7302 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007303 if (isFloat) {
7304 opCode = spv::OpGroupNonUniformFMul;
7305 } else {
7306 opCode = spv::OpGroupNonUniformIMul;
7307 }
7308 break;
7309 case glslang::EOpSubgroupMin:
7310 case glslang::EOpSubgroupInclusiveMin:
7311 case glslang::EOpSubgroupExclusiveMin:
7312 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007313 case glslang::EOpSubgroupPartitionedMin:
7314 case glslang::EOpSubgroupPartitionedInclusiveMin:
7315 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007316 if (isFloat) {
7317 opCode = spv::OpGroupNonUniformFMin;
7318 } else if (isUnsigned) {
7319 opCode = spv::OpGroupNonUniformUMin;
7320 } else {
7321 opCode = spv::OpGroupNonUniformSMin;
7322 }
7323 break;
7324 case glslang::EOpSubgroupMax:
7325 case glslang::EOpSubgroupInclusiveMax:
7326 case glslang::EOpSubgroupExclusiveMax:
7327 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007328 case glslang::EOpSubgroupPartitionedMax:
7329 case glslang::EOpSubgroupPartitionedInclusiveMax:
7330 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007331 if (isFloat) {
7332 opCode = spv::OpGroupNonUniformFMax;
7333 } else if (isUnsigned) {
7334 opCode = spv::OpGroupNonUniformUMax;
7335 } else {
7336 opCode = spv::OpGroupNonUniformSMax;
7337 }
7338 break;
7339 case glslang::EOpSubgroupAnd:
7340 case glslang::EOpSubgroupInclusiveAnd:
7341 case glslang::EOpSubgroupExclusiveAnd:
7342 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007343 case glslang::EOpSubgroupPartitionedAnd:
7344 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7345 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007346 if (isBool) {
7347 opCode = spv::OpGroupNonUniformLogicalAnd;
7348 } else {
7349 opCode = spv::OpGroupNonUniformBitwiseAnd;
7350 }
7351 break;
7352 case glslang::EOpSubgroupOr:
7353 case glslang::EOpSubgroupInclusiveOr:
7354 case glslang::EOpSubgroupExclusiveOr:
7355 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007356 case glslang::EOpSubgroupPartitionedOr:
7357 case glslang::EOpSubgroupPartitionedInclusiveOr:
7358 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007359 if (isBool) {
7360 opCode = spv::OpGroupNonUniformLogicalOr;
7361 } else {
7362 opCode = spv::OpGroupNonUniformBitwiseOr;
7363 }
7364 break;
7365 case glslang::EOpSubgroupXor:
7366 case glslang::EOpSubgroupInclusiveXor:
7367 case glslang::EOpSubgroupExclusiveXor:
7368 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007369 case glslang::EOpSubgroupPartitionedXor:
7370 case glslang::EOpSubgroupPartitionedInclusiveXor:
7371 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007372 if (isBool) {
7373 opCode = spv::OpGroupNonUniformLogicalXor;
7374 } else {
7375 opCode = spv::OpGroupNonUniformBitwiseXor;
7376 }
7377 break;
7378 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7379 case glslang::EOpSubgroupQuadSwapHorizontal:
7380 case glslang::EOpSubgroupQuadSwapVertical:
7381 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7382 default: assert(0 && "Unhandled subgroup operation!");
7383 }
7384
John Kessenich149afc32018-08-14 13:31:43 -06007385 // get the right Group Operation
7386 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007387 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007388 default:
7389 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007390 case glslang::EOpSubgroupBallotBitCount:
7391 case glslang::EOpSubgroupAdd:
7392 case glslang::EOpSubgroupMul:
7393 case glslang::EOpSubgroupMin:
7394 case glslang::EOpSubgroupMax:
7395 case glslang::EOpSubgroupAnd:
7396 case glslang::EOpSubgroupOr:
7397 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007398 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007399 break;
7400 case glslang::EOpSubgroupBallotInclusiveBitCount:
7401 case glslang::EOpSubgroupInclusiveAdd:
7402 case glslang::EOpSubgroupInclusiveMul:
7403 case glslang::EOpSubgroupInclusiveMin:
7404 case glslang::EOpSubgroupInclusiveMax:
7405 case glslang::EOpSubgroupInclusiveAnd:
7406 case glslang::EOpSubgroupInclusiveOr:
7407 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007408 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007409 break;
7410 case glslang::EOpSubgroupBallotExclusiveBitCount:
7411 case glslang::EOpSubgroupExclusiveAdd:
7412 case glslang::EOpSubgroupExclusiveMul:
7413 case glslang::EOpSubgroupExclusiveMin:
7414 case glslang::EOpSubgroupExclusiveMax:
7415 case glslang::EOpSubgroupExclusiveAnd:
7416 case glslang::EOpSubgroupExclusiveOr:
7417 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007418 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007419 break;
7420 case glslang::EOpSubgroupClusteredAdd:
7421 case glslang::EOpSubgroupClusteredMul:
7422 case glslang::EOpSubgroupClusteredMin:
7423 case glslang::EOpSubgroupClusteredMax:
7424 case glslang::EOpSubgroupClusteredAnd:
7425 case glslang::EOpSubgroupClusteredOr:
7426 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007427 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007428 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007429 case glslang::EOpSubgroupPartitionedAdd:
7430 case glslang::EOpSubgroupPartitionedMul:
7431 case glslang::EOpSubgroupPartitionedMin:
7432 case glslang::EOpSubgroupPartitionedMax:
7433 case glslang::EOpSubgroupPartitionedAnd:
7434 case glslang::EOpSubgroupPartitionedOr:
7435 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007436 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007437 break;
7438 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7439 case glslang::EOpSubgroupPartitionedInclusiveMul:
7440 case glslang::EOpSubgroupPartitionedInclusiveMin:
7441 case glslang::EOpSubgroupPartitionedInclusiveMax:
7442 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7443 case glslang::EOpSubgroupPartitionedInclusiveOr:
7444 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007445 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007446 break;
7447 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7448 case glslang::EOpSubgroupPartitionedExclusiveMul:
7449 case glslang::EOpSubgroupPartitionedExclusiveMin:
7450 case glslang::EOpSubgroupPartitionedExclusiveMax:
7451 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7452 case glslang::EOpSubgroupPartitionedExclusiveOr:
7453 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007454 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007455 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007456 }
7457
John Kessenich149afc32018-08-14 13:31:43 -06007458 // build the instruction
7459 std::vector<spv::IdImmediate> spvGroupOperands;
7460
7461 // Every operation begins with the Execution Scope operand.
7462 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7463 spvGroupOperands.push_back(executionScope);
7464
7465 // Next, for all operations that use a Group Operation, push that as an operand.
7466 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007467 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007468 spvGroupOperands.push_back(groupOperand);
7469 }
7470
John Kessenich66011cb2018-03-06 16:12:04 -07007471 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007472 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7473 spv::IdImmediate operand = { true, *opIt };
7474 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007475 }
7476
7477 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007478 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007479 switch (op) {
7480 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007481 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7482 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7483 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7484 }
7485 if (directionId != spv::NoResult) {
7486 spv::IdImmediate direction = { true, directionId };
7487 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007488 }
7489
7490 return builder.createOp(opCode, typeId, spvGroupOperands);
7491}
7492
John Kessenich8985fc92020-03-03 10:25:07 -07007493spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7494 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007495{
John Kessenich66011cb2018-03-06 16:12:04 -07007496 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7497 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007498
John Kessenich140f3df2015-06-26 16:58:36 -06007499 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007500 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007501 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007502 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007503 spv::Id typeId0 = 0;
7504 if (consumedOperands > 0)
7505 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007506 spv::Id typeId1 = 0;
7507 if (consumedOperands > 1)
7508 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007509 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007510
7511 switch (op) {
7512 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007513 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007514 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007515 else if (isUnsigned)
7516 libCall = spv::GLSLstd450UMin;
7517 else
7518 libCall = spv::GLSLstd450SMin;
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::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007522 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007523 break;
7524 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007525 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007526 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007527 else if (isUnsigned)
7528 libCall = spv::GLSLstd450UMax;
7529 else
7530 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007531 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007532 break;
7533 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007534 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007535 break;
7536 case glslang::EOpDot:
7537 opCode = spv::OpDot;
7538 break;
7539 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007540 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007541 break;
7542
7543 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007544 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007545 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007546 else if (isUnsigned)
7547 libCall = spv::GLSLstd450UClamp;
7548 else
7549 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007550 builder.promoteScalar(precision, operands.front(), operands[1]);
7551 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007552 break;
7553 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007554 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7555 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007556 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007557 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007558 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007559 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007560 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007561 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007562 break;
7563 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007564 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007565 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007566 break;
7567 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007568 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007569 builder.promoteScalar(precision, operands[0], operands[2]);
7570 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007571 break;
7572
7573 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007574 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007575 break;
7576 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007577 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007578 break;
7579 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007580 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007581 break;
7582 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007583 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007584 break;
7585 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007586 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007587 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007588 case glslang::EOpBarrier:
7589 {
7590 // This is for the extended controlBarrier function, with four operands.
7591 // The unextended barrier() goes through createNoArgOperation.
7592 assert(operands.size() == 4);
7593 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7594 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7595 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007596 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7597 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007598 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7599 spv::MemorySemanticsMakeVisibleKHRMask |
7600 spv::MemorySemanticsOutputMemoryKHRMask |
7601 spv::MemorySemanticsVolatileMask)) {
7602 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7603 }
John Kessenich8985fc92020-03-03 10:25:07 -07007604 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7605 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007606 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7607 }
7608 return 0;
7609 }
7610 break;
7611 case glslang::EOpMemoryBarrier:
7612 {
7613 // This is for the extended memoryBarrier function, with three operands.
7614 // The unextended memoryBarrier() goes through createNoArgOperation.
7615 assert(operands.size() == 3);
7616 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7617 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7618 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7619 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7620 spv::MemorySemanticsMakeVisibleKHRMask |
7621 spv::MemorySemanticsOutputMemoryKHRMask |
7622 spv::MemorySemanticsVolatileMask)) {
7623 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7624 }
7625 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7626 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7627 }
7628 return 0;
7629 }
7630 break;
7631
John Kessenicha28f7a72019-08-06 07:00:58 -06007632#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007633 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007634 if (typeProxy == glslang::EbtFloat16)
7635 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007636 libCall = spv::GLSLstd450InterpolateAtSample;
7637 break;
7638 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007639 if (typeProxy == glslang::EbtFloat16)
7640 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007641 libCall = spv::GLSLstd450InterpolateAtOffset;
7642 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007643 case glslang::EOpAddCarry:
7644 opCode = spv::OpIAddCarry;
7645 typeId = builder.makeStructResultType(typeId0, typeId0);
7646 consumedOperands = 2;
7647 break;
7648 case glslang::EOpSubBorrow:
7649 opCode = spv::OpISubBorrow;
7650 typeId = builder.makeStructResultType(typeId0, typeId0);
7651 consumedOperands = 2;
7652 break;
7653 case glslang::EOpUMulExtended:
7654 opCode = spv::OpUMulExtended;
7655 typeId = builder.makeStructResultType(typeId0, typeId0);
7656 consumedOperands = 2;
7657 break;
7658 case glslang::EOpIMulExtended:
7659 opCode = spv::OpSMulExtended;
7660 typeId = builder.makeStructResultType(typeId0, typeId0);
7661 consumedOperands = 2;
7662 break;
7663 case glslang::EOpBitfieldExtract:
7664 if (isUnsigned)
7665 opCode = spv::OpBitFieldUExtract;
7666 else
7667 opCode = spv::OpBitFieldSExtract;
7668 break;
7669 case glslang::EOpBitfieldInsert:
7670 opCode = spv::OpBitFieldInsert;
7671 break;
7672
7673 case glslang::EOpFma:
7674 libCall = spv::GLSLstd450Fma;
7675 break;
7676 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007677 {
7678 libCall = spv::GLSLstd450FrexpStruct;
7679 assert(builder.isPointerType(typeId1));
7680 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007681 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007682 if (width == 16)
7683 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7684 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007685 if (builder.getNumComponents(operands[0]) == 1)
7686 frexpIntType = builder.makeIntegerType(width, true);
7687 else
John Kessenich8985fc92020-03-03 10:25:07 -07007688 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7689 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007690 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7691 consumedOperands = 1;
7692 }
John Kessenich55e7d112015-11-15 21:33:39 -07007693 break;
7694 case glslang::EOpLdexp:
7695 libCall = spv::GLSLstd450Ldexp;
7696 break;
7697
Rex Xu574ab042016-04-14 16:53:07 +08007698 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007699 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007700
John Kessenich66011cb2018-03-06 16:12:04 -07007701 case glslang::EOpSubgroupBroadcast:
7702 case glslang::EOpSubgroupBallotBitExtract:
7703 case glslang::EOpSubgroupShuffle:
7704 case glslang::EOpSubgroupShuffleXor:
7705 case glslang::EOpSubgroupShuffleUp:
7706 case glslang::EOpSubgroupShuffleDown:
7707 case glslang::EOpSubgroupClusteredAdd:
7708 case glslang::EOpSubgroupClusteredMul:
7709 case glslang::EOpSubgroupClusteredMin:
7710 case glslang::EOpSubgroupClusteredMax:
7711 case glslang::EOpSubgroupClusteredAnd:
7712 case glslang::EOpSubgroupClusteredOr:
7713 case glslang::EOpSubgroupClusteredXor:
7714 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007715 case glslang::EOpSubgroupPartitionedAdd:
7716 case glslang::EOpSubgroupPartitionedMul:
7717 case glslang::EOpSubgroupPartitionedMin:
7718 case glslang::EOpSubgroupPartitionedMax:
7719 case glslang::EOpSubgroupPartitionedAnd:
7720 case glslang::EOpSubgroupPartitionedOr:
7721 case glslang::EOpSubgroupPartitionedXor:
7722 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7723 case glslang::EOpSubgroupPartitionedInclusiveMul:
7724 case glslang::EOpSubgroupPartitionedInclusiveMin:
7725 case glslang::EOpSubgroupPartitionedInclusiveMax:
7726 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7727 case glslang::EOpSubgroupPartitionedInclusiveOr:
7728 case glslang::EOpSubgroupPartitionedInclusiveXor:
7729 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7730 case glslang::EOpSubgroupPartitionedExclusiveMul:
7731 case glslang::EOpSubgroupPartitionedExclusiveMin:
7732 case glslang::EOpSubgroupPartitionedExclusiveMax:
7733 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7734 case glslang::EOpSubgroupPartitionedExclusiveOr:
7735 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007736 return createSubgroupOperation(op, typeId, operands, typeProxy);
7737
Rex Xu9d93a232016-05-05 12:30:44 +08007738 case glslang::EOpSwizzleInvocations:
7739 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7740 libCall = spv::SwizzleInvocationsAMD;
7741 break;
7742 case glslang::EOpSwizzleInvocationsMasked:
7743 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7744 libCall = spv::SwizzleInvocationsMaskedAMD;
7745 break;
7746 case glslang::EOpWriteInvocation:
7747 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7748 libCall = spv::WriteInvocationAMD;
7749 break;
7750
7751 case glslang::EOpMin3:
7752 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7753 if (isFloat)
7754 libCall = spv::FMin3AMD;
7755 else {
7756 if (isUnsigned)
7757 libCall = spv::UMin3AMD;
7758 else
7759 libCall = spv::SMin3AMD;
7760 }
7761 break;
7762 case glslang::EOpMax3:
7763 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7764 if (isFloat)
7765 libCall = spv::FMax3AMD;
7766 else {
7767 if (isUnsigned)
7768 libCall = spv::UMax3AMD;
7769 else
7770 libCall = spv::SMax3AMD;
7771 }
7772 break;
7773 case glslang::EOpMid3:
7774 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7775 if (isFloat)
7776 libCall = spv::FMid3AMD;
7777 else {
7778 if (isUnsigned)
7779 libCall = spv::UMid3AMD;
7780 else
7781 libCall = spv::SMid3AMD;
7782 }
7783 break;
7784
7785 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007786 if (typeProxy == glslang::EbtFloat16)
7787 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007788 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7789 libCall = spv::InterpolateAtVertexAMD;
7790 break;
Chao Chen3c366992018-09-19 11:41:59 -07007791
Daniel Kochdb32b242020-03-17 20:42:47 -04007792 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007793 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007794 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007795 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007796 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007797 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007798 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007799 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007800 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007801 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007802
7803 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007804 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7805 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007806 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007807 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7808 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007809 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007810 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7811 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007812 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007813 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7814 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007815 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007816 typeId = builder.makeBoolType();
7817 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007818 break;
7819 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007820 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007821 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007822 break;
7823 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007824 typeId = builder.makeFloatType(32);
7825 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007826 break;
7827 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007828 typeId = builder.makeIntType(32);
7829 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007830 break;
7831 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007832 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007833 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007834 break;
7835 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007836 typeId = builder.makeIntType(32);
7837 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007838 break;
7839 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007840 typeId = builder.makeIntType(32);
7841 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007842 break;
7843 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007844 typeId = builder.makeIntType(32);
7845 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007846 break;
7847 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007848 typeId = builder.makeIntType(32);
7849 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007850 break;
7851 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007852 typeId = builder.makeIntType(32);
7853 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007854 break;
7855 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007856 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7857 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007858 break;
7859 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007860 typeId = builder.makeBoolType();
7861 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007862 break;
7863 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007864 typeId = builder.makeBoolType();
7865 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007866 break;
7867 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007868 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7869 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007870 break;
7871 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007872 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7873 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007874 break;
7875 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007876 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7877 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007878 break;
7879 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007880 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7881 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007882 break;
7883 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007884 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007885 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007886 break;
7887 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007888 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007889 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007890 break;
Chao Chen3c366992018-09-19 11:41:59 -07007891 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7892 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7893 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007894 case glslang::EOpCooperativeMatrixMulAdd:
7895 opCode = spv::OpCooperativeMatrixMulAddNV;
7896 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007897#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007898 default:
7899 return 0;
7900 }
7901
7902 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007903 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007904 // Use an extended instruction from the standard library.
7905 // Construct the call arguments, without modifying the original operands vector.
7906 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7907 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007908 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007909 } else if (opCode == spv::OpDot && !isFloat) {
7910 // int dot(int, int)
7911 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7912 const int componentCount = builder.getNumComponents(operands[0]);
7913 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7914 builder.setPrecision(mulOp, precision);
7915 id = builder.createCompositeExtract(mulOp, typeId, 0);
7916 for (int i = 1; i < componentCount; ++i) {
7917 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007918 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007919 }
John Kessenich2359bd02015-12-06 19:29:11 -07007920 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007921 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007922 case 0:
7923 // should all be handled by visitAggregate and createNoArgOperation
7924 assert(0);
7925 return 0;
7926 case 1:
7927 // should all be handled by createUnaryOperation
7928 assert(0);
7929 return 0;
7930 case 2:
7931 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7932 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007933 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007934 // anything 3 or over doesn't have l-value operands, so all should be consumed
7935 assert(consumedOperands == operands.size());
7936 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007937 break;
7938 }
7939 }
7940
John Kessenichb9197c82019-08-11 07:41:45 -06007941#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007942 // Decode the return types that were structures
7943 switch (op) {
7944 case glslang::EOpAddCarry:
7945 case glslang::EOpSubBorrow:
7946 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7947 id = builder.createCompositeExtract(id, typeId0, 0);
7948 break;
7949 case glslang::EOpUMulExtended:
7950 case glslang::EOpIMulExtended:
7951 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7952 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7953 break;
7954 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007955 {
7956 assert(operands.size() == 2);
7957 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7958 // "exp" is floating-point type (from HLSL intrinsic)
7959 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7960 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7961 builder.createStore(member1, operands[1]);
7962 } else
7963 // "exp" is integer type (from GLSL built-in function)
7964 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7965 id = builder.createCompositeExtract(id, typeId0, 0);
7966 }
John Kessenich55e7d112015-11-15 21:33:39 -07007967 break;
7968 default:
7969 break;
7970 }
John Kessenichb9197c82019-08-11 07:41:45 -06007971#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007972
John Kessenich32cfd492016-02-02 12:37:46 -07007973 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007974}
7975
Rex Xu9d93a232016-05-05 12:30:44 +08007976// Intrinsics with no arguments (or no return value, and no precision).
7977spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007978{
Jeff Bolz36831c92018-09-05 10:11:41 -05007979 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007980 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7981 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007982
7983 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007984 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007985 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007986 if (glslangIntermediate->usingVulkanMemoryModel()) {
7987 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7988 spv::MemorySemanticsOutputMemoryKHRMask |
7989 spv::MemorySemanticsAcquireReleaseMask);
7990 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7991 } else {
7992 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7993 }
John Kessenich82979362017-12-11 04:02:24 -07007994 } else {
7995 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7996 spv::MemorySemanticsWorkgroupMemoryMask |
7997 spv::MemorySemanticsAcquireReleaseMask);
7998 }
John Kessenich140f3df2015-06-26 16:58:36 -06007999 return 0;
8000 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05008001 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
8002 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008003 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008004 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05008005 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
8006 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008007 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008008 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05008009 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
8010 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008011 return 0;
8012 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07008013 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
8014 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008015 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06008016#ifndef GLSLANG_WEB
8017 case glslang::EOpMemoryBarrierAtomicCounter:
8018 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
8019 spv::MemorySemanticsAcquireReleaseMask);
8020 return 0;
8021 case glslang::EOpMemoryBarrierImage:
8022 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8023 spv::MemorySemanticsAcquireReleaseMask);
8024 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008025 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008026 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008027 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008028 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008029 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008030 case glslang::EOpDeviceMemoryBarrier:
8031 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8032 spv::MemorySemanticsImageMemoryMask |
8033 spv::MemorySemanticsAcquireReleaseMask);
8034 return 0;
8035 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8036 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8037 spv::MemorySemanticsImageMemoryMask |
8038 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008039 return 0;
8040 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008041 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8042 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008043 return 0;
8044 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008045 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8046 spv::MemorySemanticsWorkgroupMemoryMask |
8047 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008048 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008049 case glslang::EOpSubgroupBarrier:
8050 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8051 spv::MemorySemanticsAcquireReleaseMask);
8052 return spv::NoResult;
8053 case glslang::EOpSubgroupMemoryBarrier:
8054 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8055 spv::MemorySemanticsAcquireReleaseMask);
8056 return spv::NoResult;
8057 case glslang::EOpSubgroupMemoryBarrierBuffer:
8058 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8059 spv::MemorySemanticsAcquireReleaseMask);
8060 return spv::NoResult;
8061 case glslang::EOpSubgroupMemoryBarrierImage:
8062 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8063 spv::MemorySemanticsAcquireReleaseMask);
8064 return spv::NoResult;
8065 case glslang::EOpSubgroupMemoryBarrierShared:
8066 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8067 spv::MemorySemanticsAcquireReleaseMask);
8068 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008069
8070 case glslang::EOpEmitVertex:
8071 builder.createNoResultOp(spv::OpEmitVertex);
8072 return 0;
8073 case glslang::EOpEndPrimitive:
8074 builder.createNoResultOp(spv::OpEndPrimitive);
8075 return 0;
8076
John Kessenich66011cb2018-03-06 16:12:04 -07008077 case glslang::EOpSubgroupElect: {
8078 std::vector<spv::Id> operands;
8079 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8080 }
Rex Xu9d93a232016-05-05 12:30:44 +08008081 case glslang::EOpTime:
8082 {
8083 std::vector<spv::Id> args; // Dummy arguments
8084 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8085 return builder.setPrecision(id, precision);
8086 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008087 case glslang::EOpIgnoreIntersection:
8088 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008089 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008090 case glslang::EOpTerminateRay:
8091 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008092 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008093 case glslang::EOpRayQueryInitialize:
8094 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8095 return 0;
8096 case glslang::EOpRayQueryTerminate:
8097 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8098 return 0;
8099 case glslang::EOpRayQueryGenerateIntersection:
8100 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8101 return 0;
8102 case glslang::EOpRayQueryConfirmIntersection:
8103 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8104 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008105 case glslang::EOpBeginInvocationInterlock:
8106 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8107 return 0;
8108 case glslang::EOpEndInvocationInterlock:
8109 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8110 return 0;
8111
Jeff Bolzba6170b2019-07-01 09:23:23 -05008112 case glslang::EOpIsHelperInvocation:
8113 {
8114 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008115 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8116 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8117 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008118 }
8119
amhagan91fb0092019-07-10 21:14:38 -04008120 case glslang::EOpReadClockSubgroupKHR: {
8121 std::vector<spv::Id> args;
8122 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8123 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8124 builder.addCapability(spv::CapabilityShaderClockKHR);
8125 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8126 }
8127
8128 case glslang::EOpReadClockDeviceKHR: {
8129 std::vector<spv::Id> args;
8130 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8131 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8132 builder.addCapability(spv::CapabilityShaderClockKHR);
8133 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8134 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008135#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008136 default:
John Kessenich155d3512019-08-08 23:29:20 -06008137 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008138 }
John Kessenich155d3512019-08-08 23:29:20 -06008139
8140 logger->missingFunctionality("unknown operation with no arguments");
8141
8142 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008143}
8144
8145spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8146{
John Kessenich2f273362015-07-18 22:34:27 -06008147 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008148 spv::Id id;
8149 if (symbolValues.end() != iter) {
8150 id = iter->second;
8151 return id;
8152 }
8153
8154 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008155 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008156 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008157 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008158 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008159 if (forcedType.second != spv::NoType)
8160 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008161
Rex Xuc884b4a2016-06-29 15:03:44 +08008162 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008163 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8164 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8165 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008166#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008167 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008168 if (symbol->getQualifier().hasComponent())
8169 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8170 if (symbol->getQualifier().hasIndex())
8171 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008172#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008173 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008174 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008175 // atomic counters use this:
8176 if (symbol->getQualifier().hasOffset())
8177 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008178 }
8179
scygan2c864272016-05-18 18:09:17 +02008180 if (symbol->getQualifier().hasLocation())
8181 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008182 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008183 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008184 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008185 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008186 }
John Kessenich140f3df2015-06-26 16:58:36 -06008187 if (symbol->getQualifier().hasSet())
8188 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008189 else if (IsDescriptorResource(symbol->getType())) {
8190 // default to 0
8191 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8192 }
John Kessenich140f3df2015-06-26 16:58:36 -06008193 if (symbol->getQualifier().hasBinding())
8194 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008195 else if (IsDescriptorResource(symbol->getType())) {
8196 // default to 0
8197 builder.addDecoration(id, spv::DecorationBinding, 0);
8198 }
John Kessenich6c292d32016-02-15 20:58:50 -07008199 if (symbol->getQualifier().hasAttachment())
8200 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008201 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008202 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008203 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008204 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008205 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8206 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8207 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8208 }
8209 if (symbol->getQualifier().hasXfbOffset())
8210 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008211 }
8212
John Kessenichb9197c82019-08-11 07:41:45 -06008213 // add built-in variable decoration
8214 if (builtIn != spv::BuiltInMax) {
8215 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8216 }
8217
8218#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008219 if (symbol->getType().isImage()) {
8220 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008221 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8222 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008223 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008224 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008225 }
8226
John Kessenich5611c6d2018-04-05 11:25:02 -06008227 // nonuniform
8228 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8229
chaoc0ad6a4e2016-12-19 16:29:34 -08008230 if (builtIn == spv::BuiltInSampleMask) {
8231 spv::Decoration decoration;
8232 // GL_NV_sample_mask_override_coverage extension
8233 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008234 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008235 else
8236 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008237 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008238 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008239 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008240 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8241 }
8242 }
chaoc771d89f2017-01-13 01:10:53 -08008243 else if (builtIn == spv::BuiltInLayer) {
8244 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008245 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008246 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008247 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8248 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8249 }
John Kessenichb41bff62017-08-11 13:07:17 -06008250 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008251 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8252 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008253 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8254 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8255 }
8256 }
8257
chaoc6e5acae2016-12-20 13:28:52 -08008258 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008259 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008260 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008261 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8262 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008263 if (symbol->getQualifier().pervertexNV) {
8264 builder.addDecoration(id, spv::DecorationPerVertexNV);
8265 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8266 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8267 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008268
John Kessenich5d610ee2018-03-07 18:05:55 -07008269 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8270 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8271 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8272 symbol->getType().getQualifier().semanticName);
8273 }
8274
John Kessenich7015bd62019-08-01 03:28:08 -06008275 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008276 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8277 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008278 }
John Kessenichb9197c82019-08-11 07:41:45 -06008279#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008280
John Kessenich140f3df2015-06-26 16:58:36 -06008281 return id;
8282}
8283
John Kessenicha28f7a72019-08-06 07:00:58 -06008284#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008285// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8286void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8287{
8288 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008289 if (qualifier.perPrimitiveNV) {
8290 // Need to add capability/extension for fragment shader.
8291 // Mesh shader already adds this by default.
8292 if (glslangIntermediate->getStage() == EShLangFragment) {
8293 builder.addCapability(spv::CapabilityMeshShadingNV);
8294 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8295 }
Chao Chen3c366992018-09-19 11:41:59 -07008296 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008297 }
Chao Chen3c366992018-09-19 11:41:59 -07008298 if (qualifier.perViewNV)
8299 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8300 if (qualifier.perTaskNV)
8301 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8302 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008303 if (qualifier.perPrimitiveNV) {
8304 // Need to add capability/extension for fragment shader.
8305 // Mesh shader already adds this by default.
8306 if (glslangIntermediate->getStage() == EShLangFragment) {
8307 builder.addCapability(spv::CapabilityMeshShadingNV);
8308 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8309 }
Chao Chen3c366992018-09-19 11:41:59 -07008310 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008311 }
Chao Chen3c366992018-09-19 11:41:59 -07008312 if (qualifier.perViewNV)
8313 builder.addDecoration(id, spv::DecorationPerViewNV);
8314 if (qualifier.perTaskNV)
8315 builder.addDecoration(id, spv::DecorationPerTaskNV);
8316 }
8317}
8318#endif
8319
John Kessenich55e7d112015-11-15 21:33:39 -07008320// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008321// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008322//
8323// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8324//
8325// Recursively walk the nodes. The nodes form a tree whose leaves are
8326// regular constants, which themselves are trees that createSpvConstant()
8327// recursively walks. So, this function walks the "top" of the tree:
8328// - emit specialization constant-building instructions for specConstant
8329// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008330spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008331{
John Kessenich7cc0e282016-03-20 00:46:02 -06008332 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008333
qining4f4bb812016-04-03 23:55:17 -04008334 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008335 if (! node.getQualifier().specConstant) {
8336 // hand off to the non-spec-constant path
8337 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8338 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008339 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8340 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8341 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008342 }
8343
8344 // We now know we have a specialization constant to build
8345
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008346 // Extra capabilities may be needed.
8347 if (node.getType().contains8BitInt())
8348 builder.addCapability(spv::CapabilityInt8);
8349 if (node.getType().contains16BitFloat())
8350 builder.addCapability(spv::CapabilityFloat16);
8351 if (node.getType().contains16BitInt())
8352 builder.addCapability(spv::CapabilityInt16);
8353 if (node.getType().contains64BitInt())
8354 builder.addCapability(spv::CapabilityInt64);
8355 if (node.getType().containsDouble())
8356 builder.addCapability(spv::CapabilityFloat64);
8357
John Kessenichd94c0032016-05-30 19:29:40 -06008358 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008359 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8360 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8361 std::vector<spv::Id> dimConstId;
8362 for (int dim = 0; dim < 3; ++dim) {
8363 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8364 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008365 if (specConst) {
8366 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8367 glslangIntermediate->getLocalSizeSpecId(dim));
8368 }
qining4f4bb812016-04-03 23:55:17 -04008369 }
8370 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8371 }
8372
8373 // An AST node labelled as specialization constant should be a symbol node.
8374 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8375 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008376 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008377 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008378 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8379 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8380 // will set the builder into spec constant op instruction generating mode.
8381 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008382 result = accessChainLoad(sub_tree->getType());
8383 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008384 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008385 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008386 } else {
8387 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008388 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008389 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008390 builder.addName(result, sn->getName().c_str());
8391 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008392 }
qining4f4bb812016-04-03 23:55:17 -04008393
8394 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8395 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008396 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008397 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008398}
8399
John Kessenich140f3df2015-06-26 16:58:36 -06008400// Use 'consts' as the flattened glslang source of scalar constants to recursively
8401// build the aggregate SPIR-V constant.
8402//
8403// If there are not enough elements present in 'consts', 0 will be substituted;
8404// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8405//
John Kessenich8985fc92020-03-03 10:25:07 -07008406spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8407 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008408{
8409 // vector of constants for SPIR-V
8410 std::vector<spv::Id> spvConsts;
8411
8412 // Type is used for struct and array constants
8413 spv::Id typeId = convertGlslangToSpvType(glslangType);
8414
8415 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008416 glslang::TType elementType(glslangType, 0);
8417 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008418 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008419 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008420 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008421 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008422 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008423 } else if (glslangType.isCoopMat()) {
8424 glslang::TType componentType(glslangType.getBasicType());
8425 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008426 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008427 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8428 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008429 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008430 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008431 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8432 bool zero = nextConst >= consts.size();
8433 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008434 case glslang::EbtInt:
8435 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8436 break;
8437 case glslang::EbtUint:
8438 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8439 break;
8440 case glslang::EbtFloat:
8441 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8442 break;
8443 case glslang::EbtBool:
8444 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8445 break;
8446#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008447 case glslang::EbtInt8:
8448 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8449 break;
8450 case glslang::EbtUint8:
8451 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8452 break;
8453 case glslang::EbtInt16:
8454 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8455 break;
8456 case glslang::EbtUint16:
8457 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8458 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008459 case glslang::EbtInt64:
8460 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8461 break;
8462 case glslang::EbtUint64:
8463 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8464 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008465 case glslang::EbtDouble:
8466 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8467 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008468 case glslang::EbtFloat16:
8469 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8470 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008471#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008472 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008473 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008474 break;
8475 }
8476 ++nextConst;
8477 }
8478 } else {
8479 // we have a non-aggregate (scalar) constant
8480 bool zero = nextConst >= consts.size();
8481 spv::Id scalar = 0;
8482 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008483 case glslang::EbtInt:
8484 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8485 break;
8486 case glslang::EbtUint:
8487 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8488 break;
8489 case glslang::EbtFloat:
8490 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8491 break;
8492 case glslang::EbtBool:
8493 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8494 break;
8495#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008496 case glslang::EbtInt8:
8497 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8498 break;
8499 case glslang::EbtUint8:
8500 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8501 break;
8502 case glslang::EbtInt16:
8503 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8504 break;
8505 case glslang::EbtUint16:
8506 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8507 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008508 case glslang::EbtInt64:
8509 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8510 break;
8511 case glslang::EbtUint64:
8512 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8513 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008514 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008515 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008516 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008517 case glslang::EbtFloat16:
8518 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8519 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008520 case glslang::EbtReference:
8521 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8522 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8523 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008524#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008525 case glslang::EbtString:
8526 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8527 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008528 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008529 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008530 break;
8531 }
8532 ++nextConst;
8533 return scalar;
8534 }
8535
8536 return builder.makeCompositeConstant(typeId, spvConsts);
8537}
8538
John Kessenich7c1aa102015-10-15 13:29:11 -06008539// Return true if the node is a constant or symbol whose reading has no
8540// non-trivial observable cost or effect.
8541bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8542{
8543 // don't know what this is
8544 if (node == nullptr)
8545 return false;
8546
8547 // a constant is safe
8548 if (node->getAsConstantUnion() != nullptr)
8549 return true;
8550
8551 // not a symbol means non-trivial
8552 if (node->getAsSymbolNode() == nullptr)
8553 return false;
8554
8555 // a symbol, depends on what's being read
8556 switch (node->getType().getQualifier().storage) {
8557 case glslang::EvqTemporary:
8558 case glslang::EvqGlobal:
8559 case glslang::EvqIn:
8560 case glslang::EvqInOut:
8561 case glslang::EvqConst:
8562 case glslang::EvqConstReadOnly:
8563 case glslang::EvqUniform:
8564 return true;
8565 default:
8566 return false;
8567 }
qining25262b32016-05-06 17:25:16 -04008568}
John Kessenich7c1aa102015-10-15 13:29:11 -06008569
8570// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008571// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008572// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008573// Return true if trivial.
8574bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8575{
8576 if (node == nullptr)
8577 return false;
8578
John Kessenich84cc15f2017-05-24 16:44:47 -06008579 // count non scalars as trivial, as well as anything coming from HLSL
8580 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008581 return true;
8582
John Kessenich7c1aa102015-10-15 13:29:11 -06008583 // symbols and constants are trivial
8584 if (isTrivialLeaf(node))
8585 return true;
8586
8587 // otherwise, it needs to be a simple operation or one or two leaf nodes
8588
8589 // not a simple operation
8590 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8591 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8592 if (binaryNode == nullptr && unaryNode == nullptr)
8593 return false;
8594
8595 // not on leaf nodes
8596 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8597 return false;
8598
8599 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8600 return false;
8601 }
8602
8603 switch (node->getAsOperator()->getOp()) {
8604 case glslang::EOpLogicalNot:
8605 case glslang::EOpConvIntToBool:
8606 case glslang::EOpConvUintToBool:
8607 case glslang::EOpConvFloatToBool:
8608 case glslang::EOpConvDoubleToBool:
8609 case glslang::EOpEqual:
8610 case glslang::EOpNotEqual:
8611 case glslang::EOpLessThan:
8612 case glslang::EOpGreaterThan:
8613 case glslang::EOpLessThanEqual:
8614 case glslang::EOpGreaterThanEqual:
8615 case glslang::EOpIndexDirect:
8616 case glslang::EOpIndexDirectStruct:
8617 case glslang::EOpLogicalXor:
8618 case glslang::EOpAny:
8619 case glslang::EOpAll:
8620 return true;
8621 default:
8622 return false;
8623 }
8624}
8625
8626// Emit short-circuiting code, where 'right' is never evaluated unless
8627// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008628spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8629 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008630{
8631 spv::Id boolTypeId = builder.makeBoolType();
8632
8633 // emit left operand
8634 builder.clearAccessChain();
8635 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008636 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008637
8638 // Operands to accumulate OpPhi operands
8639 std::vector<spv::Id> phiOperands;
8640 // accumulate left operand's phi information
8641 phiOperands.push_back(leftId);
8642 phiOperands.push_back(builder.getBuildPoint()->getId());
8643
8644 // Make the two kinds of operation symmetric with a "!"
8645 // || => emit "if (! left) result = right"
8646 // && => emit "if ( left) result = right"
8647 //
8648 // TODO: this runtime "not" for || could be avoided by adding functionality
8649 // to 'builder' to have an "else" without an "then"
8650 if (op == glslang::EOpLogicalOr)
8651 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8652
8653 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008654 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008655
8656 // emit right operand as the "then" part of the "if"
8657 builder.clearAccessChain();
8658 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008659 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008660
8661 // accumulate left operand's phi information
8662 phiOperands.push_back(rightId);
8663 phiOperands.push_back(builder.getBuildPoint()->getId());
8664
8665 // finish the "if"
8666 ifBuilder.makeEndIf();
8667
8668 // phi together the two results
8669 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8670}
8671
John Kessenicha28f7a72019-08-06 07:00:58 -06008672#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008673// Return type Id of the imported set of extended instructions corresponds to the name.
8674// Import this set if it has not been imported yet.
8675spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8676{
8677 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8678 return extBuiltinMap[name];
8679 else {
Rex Xu51596642016-09-21 18:56:12 +08008680 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008681 spv::Id extBuiltins = builder.import(name);
8682 extBuiltinMap[name] = extBuiltins;
8683 return extBuiltins;
8684 }
8685}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008686#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008687
John Kessenich140f3df2015-06-26 16:58:36 -06008688}; // end anonymous namespace
8689
8690namespace glslang {
8691
John Kessenich68d78fd2015-07-12 19:28:10 -06008692void GetSpirvVersion(std::string& version)
8693{
John Kessenich9e55f632015-07-15 10:03:39 -06008694 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008695 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008696 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008697 version = buf;
8698}
8699
John Kessenicha372a3e2017-11-02 22:32:14 -06008700// For low-order part of the generator's magic number. Bump up
8701// when there is a change in the style (e.g., if SSA form changes,
8702// or a different instruction sequence to do something gets used).
8703int GetSpirvGeneratorVersion()
8704{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008705 // return 1; // start
8706 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008707 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008708 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008709 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008710 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8711 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008712 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008713 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008714 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8715 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008716}
8717
John Kessenich140f3df2015-06-26 16:58:36 -06008718// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008719void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008720{
8721 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008722 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008723 if (out.fail())
8724 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008725 for (int i = 0; i < (int)spirv.size(); ++i) {
8726 unsigned int word = spirv[i];
8727 out.write((const char*)&word, 4);
8728 }
8729 out.close();
8730}
8731
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008732// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008733void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008734{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008735#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008736 std::ofstream out;
8737 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008738 if (out.fail())
8739 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008740 out << "\t// " <<
8741 GetSpirvGeneratorVersion() <<
8742 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8743 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008744 if (varName != nullptr) {
8745 out << "\t #pragma once" << std::endl;
8746 out << "const uint32_t " << varName << "[] = {" << std::endl;
8747 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008748 const int WORDS_PER_LINE = 8;
8749 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8750 out << "\t";
8751 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8752 const unsigned int word = spirv[i + j];
8753 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8754 if (i + j + 1 < (int)spirv.size()) {
8755 out << ",";
8756 }
8757 }
8758 out << std::endl;
8759 }
Flavio15017db2017-02-15 14:29:33 -08008760 if (varName != nullptr) {
8761 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008762 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008763 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008764 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008765#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008766}
8767
John Kessenich140f3df2015-06-26 16:58:36 -06008768//
8769// Set up the glslang traversal
8770//
John Kessenich4e11b612018-08-30 16:56:59 -06008771void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008772{
Lei Zhang17535f72016-05-04 15:55:59 -04008773 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008774 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008775}
8776
John Kessenich4e11b612018-08-30 16:56:59 -06008777void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008778 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008779{
John Kessenich140f3df2015-06-26 16:58:36 -06008780 TIntermNode* root = intermediate.getTreeRoot();
8781
8782 if (root == 0)
8783 return;
8784
John Kessenich4e11b612018-08-30 16:56:59 -06008785 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008786 if (options == nullptr)
8787 options = &defaultOptions;
8788
John Kessenich4e11b612018-08-30 16:56:59 -06008789 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008790
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008791 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008792 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008793 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008794 it.dumpSpv(spirv);
8795
GregFfb03a552018-03-29 11:49:14 -06008796#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008797 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8798 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008799 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008800 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8801 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008802 prelegalization = false;
8803 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008804 else if (options->stripDebugInfo) {
8805 // Strip debug info even if optimization is disabled.
8806 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8807 }
John Kessenich717c80a2018-08-23 15:17:10 -06008808
John Kessenich4e11b612018-08-30 16:56:59 -06008809 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008810 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008811
John Kessenich717c80a2018-08-23 15:17:10 -06008812 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008813 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008814
GregFcd1f1692017-09-21 18:40:22 -06008815#endif
8816
John Kessenich4e11b612018-08-30 16:56:59 -06008817 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008818}
8819
8820}; // end namespace glslang