blob: 18d64f9ce431b91ba9aa044bc7b2e3e12d8bca38 [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;
286#endif
287
John Kessenich66e2faf2016-03-12 18:34:36 -0700288 switch (source) {
289 case glslang::EShSourceGlsl:
290 switch (profile) {
291 case ENoProfile:
292 case ECoreProfile:
293 case ECompatibilityProfile:
294 return spv::SourceLanguageGLSL;
295 case EEsProfile:
296 return spv::SourceLanguageESSL;
297 default:
298 return spv::SourceLanguageUnknown;
299 }
300 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600301 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 default:
303 return spv::SourceLanguageUnknown;
304 }
305}
306
307// Translate glslang language (stage) to SPIR-V execution model.
308spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
309{
310 switch (stage) {
311 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600312 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600313 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600314#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600315 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
316 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
317 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400318 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
319 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
320 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
321 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
322 case EShLangMiss: return spv::ExecutionModelMissKHR;
323 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700324 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
325 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
326#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600327 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700328 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600329 return spv::ExecutionModelFragment;
330 }
331}
332
John Kessenich140f3df2015-06-26 16:58:36 -0600333// Translate glslang sampler type to SPIR-V dimensionality.
334spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
335{
336 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700337 case glslang::Esd1D: return spv::Dim1D;
338 case glslang::Esd2D: return spv::Dim2D;
339 case glslang::Esd3D: return spv::Dim3D;
340 case glslang::EsdCube: return spv::DimCube;
341 case glslang::EsdRect: return spv::DimRect;
342 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700343 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 return spv::Dim2D;
347 }
348}
349
John Kessenichf6640762016-08-01 19:44:00 -0600350// Translate glslang precision to SPIR-V precision decorations.
351spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600352{
John Kessenichf6640762016-08-01 19:44:00 -0600353 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700354 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600355 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600356 default:
357 return spv::NoPrecision;
358 }
359}
360
John Kessenichf6640762016-08-01 19:44:00 -0600361// Translate glslang type to SPIR-V precision decorations.
362spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
363{
364 return TranslatePrecisionDecoration(type.getQualifier().precision);
365}
366
John Kessenich140f3df2015-06-26 16:58:36 -0600367// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600368spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600369{
370 if (type.getBasicType() == glslang::EbtBlock) {
371 switch (type.getQualifier().storage) {
372 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600373 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600374 case glslang::EvqVaryingIn: return spv::DecorationBlock;
375 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600376#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400377 case glslang::EvqPayload: return spv::DecorationBlock;
378 case glslang::EvqPayloadIn: return spv::DecorationBlock;
379 case glslang::EvqHitAttr: return spv::DecorationBlock;
380 case glslang::EvqCallableData: return spv::DecorationBlock;
381 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700382#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600383 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700384 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600385 break;
386 }
387 }
388
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600390}
391
Rex Xu1da878f2016-02-21 20:59:01 +0800392// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700393void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
394 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800395{
Jeff Bolz36831c92018-09-05 10:11:41 -0500396 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600397 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500398 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600399 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500400 memory.push_back(spv::DecorationVolatile);
401 memory.push_back(spv::DecorationCoherent);
402 }
John Kessenich14b85d32018-06-04 15:36:03 -0600403 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600404 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800405 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600406 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800407 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600408 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800409 memory.push_back(spv::DecorationNonReadable);
410}
411
John Kessenich140f3df2015-06-26 16:58:36 -0600412// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700413spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600414{
415 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700416 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600417 case glslang::ElmRowMajor:
418 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700419 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600420 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700421 default:
422 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600424 }
425 } else {
426 switch (type.getBasicType()) {
427 default:
John Kessenich4016e382016-07-15 11:53:56 -0600428 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600429 break;
430 case glslang::EbtBlock:
431 switch (type.getQualifier().storage) {
432 case glslang::EvqUniform:
433 case glslang::EvqBuffer:
434 switch (type.getQualifier().layoutPacking) {
435 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600436 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
437 default:
John Kessenich4016e382016-07-15 11:53:56 -0600438 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600439 }
440 case glslang::EvqVaryingIn:
441 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700442 if (type.getQualifier().isTaskMemory()) {
443 switch (type.getQualifier().layoutPacking) {
444 case glslang::ElpShared: return spv::DecorationGLSLShared;
445 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
446 default: break;
447 }
448 } else {
449 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
450 }
John Kessenich4016e382016-07-15 11:53:56 -0600451 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600452#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400453 case glslang::EvqPayload:
454 case glslang::EvqPayloadIn:
455 case glslang::EvqHitAttr:
456 case glslang::EvqCallableData:
457 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700458 return spv::DecorationMax;
459#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600460 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700461 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600462 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600463 }
464 }
465 }
466}
467
468// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600469// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700470// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800471spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600472{
Rex Xubbceed72016-05-21 09:40:44 +0800473 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700474 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600475 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600476 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700477 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700478 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600479 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600480 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800481 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800482 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800483 }
Rex Xubbceed72016-05-21 09:40:44 +0800484 else
John Kessenich4016e382016-07-15 11:53:56 -0600485 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800486}
487
488// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600489// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800490// should be applied.
491spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
492{
John Kessenichb9197c82019-08-11 07:41:45 -0600493 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600494 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600495#ifndef GLSLANG_WEB
496 else if (qualifier.patch)
497 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700498 else if (qualifier.sample) {
499 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600500 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600501 }
502#endif
503
504 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600505}
506
John Kessenich92187592016-02-01 13:45:25 -0700507// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700508spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600509{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700510 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600511 return spv::DecorationInvariant;
512 else
John Kessenich4016e382016-07-15 11:53:56 -0600513 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600514}
515
qining9220dbb2016-05-04 17:34:38 -0400516// If glslang type is noContraction, return SPIR-V NoContraction decoration.
517spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
518{
John Kessenichb9197c82019-08-11 07:41:45 -0600519#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600520 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400521 return spv::DecorationNoContraction;
522 else
John Kessenichb9197c82019-08-11 07:41:45 -0600523#endif
John Kessenich4016e382016-07-15 11:53:56 -0600524 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400525}
526
John Kessenich5611c6d2018-04-05 11:25:02 -0600527// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
528spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
529{
John Kessenichb9197c82019-08-11 07:41:45 -0600530#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600531 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600532 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600533 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
534 return spv::DecorationNonUniformEXT;
535 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600536#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600537 return spv::DecorationMax;
538}
539
John Kessenichb9197c82019-08-11 07:41:45 -0600540spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
541 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500542{
Jeff Bolz36831c92018-09-05 10:11:41 -0500543 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600544
545#ifndef GLSLANG_WEB
546 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
547 return mask;
548
Daniel Kochdb32b242020-03-17 20:42:47 -0400549 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500550 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
551 spv::MemoryAccessMakePointerVisibleKHRMask;
552 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400553
Jeff Bolz36831c92018-09-05 10:11:41 -0500554 if (coherentFlags.nonprivate) {
555 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
556 }
557 if (coherentFlags.volatil) {
558 mask = mask | spv::MemoryAccessVolatileMask;
559 }
560 if (mask != spv::MemoryAccessMaskNone) {
561 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
562 }
John Kessenichb9197c82019-08-11 07:41:45 -0600563#endif
564
Jeff Bolz36831c92018-09-05 10:11:41 -0500565 return mask;
566}
567
John Kessenichb9197c82019-08-11 07:41:45 -0600568spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
569 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500570{
Jeff Bolz36831c92018-09-05 10:11:41 -0500571 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600572
573#ifndef GLSLANG_WEB
574 if (!glslangIntermediate->usingVulkanMemoryModel())
575 return mask;
576
Jeff Bolz36831c92018-09-05 10:11:41 -0500577 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400578 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500579 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
580 spv::ImageOperandsMakeTexelVisibleKHRMask;
581 }
582 if (coherentFlags.nonprivate) {
583 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
584 }
585 if (coherentFlags.volatil) {
586 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
587 }
588 if (mask != spv::ImageOperandsMaskNone) {
589 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
590 }
John Kessenichb9197c82019-08-11 07:41:45 -0600591#endif
592
Jeff Bolz36831c92018-09-05 10:11:41 -0500593 return mask;
594}
595
596spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
597{
John Kessenichb9197c82019-08-11 07:41:45 -0600598 spv::Builder::AccessChain::CoherentFlags flags = {};
599#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500600 flags.coherent = type.getQualifier().coherent;
601 flags.devicecoherent = type.getQualifier().devicecoherent;
602 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
603 // shared variables are implicitly workgroupcoherent in GLSL.
604 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
605 type.getQualifier().storage == glslang::EvqShared;
606 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400607 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600608 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500609 // *coherent variables are implicitly nonprivate in GLSL
610 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400611 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600612 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500613 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600614#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500615 return flags;
616}
617
John Kessenichb9197c82019-08-11 07:41:45 -0600618spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
619 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500620{
John Kessenichb9197c82019-08-11 07:41:45 -0600621 spv::Scope scope = spv::ScopeMax;
622
623#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600624 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500625 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
626 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
627 } else if (coherentFlags.devicecoherent) {
628 scope = spv::ScopeDevice;
629 } else if (coherentFlags.queuefamilycoherent) {
630 scope = spv::ScopeQueueFamilyKHR;
631 } else if (coherentFlags.workgroupcoherent) {
632 scope = spv::ScopeWorkgroup;
633 } else if (coherentFlags.subgroupcoherent) {
634 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400635 } else if (coherentFlags.shadercallcoherent) {
636 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500637 }
638 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
639 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
640 }
John Kessenichb9197c82019-08-11 07:41:45 -0600641#endif
642
Jeff Bolz36831c92018-09-05 10:11:41 -0500643 return scope;
644}
645
David Netoa901ffe2016-06-08 14:11:40 +0100646// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
647// associated capabilities when required. For some built-in variables, a capability
648// is generated only when using the variable in an executable instruction, but not when
649// just declaring a struct member variable with it. This is true for PointSize,
650// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700651spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
652 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600653{
654 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700655 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600656#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600657 // Defer adding the capability until the built-in is actually used.
658 if (! memberDeclaration) {
659 switch (glslangIntermediate->getStage()) {
660 case EShLangGeometry:
661 builder.addCapability(spv::CapabilityGeometryPointSize);
662 break;
663 case EShLangTessControl:
664 case EShLangTessEvaluation:
665 builder.addCapability(spv::CapabilityTessellationPointSize);
666 break;
667 default:
668 break;
669 }
John Kessenich92187592016-02-01 13:45:25 -0700670 }
John Kessenich155d3512019-08-08 23:29:20 -0600671#endif
John Kessenich92187592016-02-01 13:45:25 -0700672 return spv::BuiltInPointSize;
673
John Kessenicha28f7a72019-08-06 07:00:58 -0600674 case glslang::EbvPosition: return spv::BuiltInPosition;
675 case glslang::EbvVertexId: return spv::BuiltInVertexId;
676 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
677 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
678 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
679
680 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
681 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
682 case glslang::EbvFace: return spv::BuiltInFrontFacing;
683 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
684
John Kessenich3dd1ce52019-10-17 07:08:40 -0600685 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
686 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
687 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
688 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
689 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
690 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
691
John Kessenicha28f7a72019-08-06 07:00:58 -0600692#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600693 // These *Distance capabilities logically belong here, but if the member is declared and
694 // then never used, consumers of SPIR-V prefer the capability not be declared.
695 // They are now generated when used, rather than here when declared.
696 // Potentially, the specification should be more clear what the minimum
697 // use needed is to trigger the capability.
698 //
John Kessenich92187592016-02-01 13:45:25 -0700699 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100700 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800701 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700702 return spv::BuiltInClipDistance;
703
704 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100705 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800706 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700707 return spv::BuiltInCullDistance;
708
709 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600710 builder.addCapability(spv::CapabilityMultiViewport);
711 if (glslangIntermediate->getStage() == EShLangVertex ||
712 glslangIntermediate->getStage() == EShLangTessControl ||
713 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800714
John Kessenich8317e6c2019-08-18 23:58:08 -0600715 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600716 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800717 }
John Kessenich92187592016-02-01 13:45:25 -0700718 return spv::BuiltInViewportIndex;
719
John Kessenich5e801132016-02-15 11:09:46 -0700720 case glslang::EbvSampleId:
721 builder.addCapability(spv::CapabilitySampleRateShading);
722 return spv::BuiltInSampleId;
723
724 case glslang::EbvSamplePosition:
725 builder.addCapability(spv::CapabilitySampleRateShading);
726 return spv::BuiltInSamplePosition;
727
728 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700729 return spv::BuiltInSampleMask;
730
John Kessenich78a45572016-07-08 14:05:15 -0600731 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700732 if (glslangIntermediate->getStage() == EShLangMeshNV) {
733 return spv::BuiltInLayer;
734 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600735 builder.addCapability(spv::CapabilityGeometry);
736 if (glslangIntermediate->getStage() == EShLangVertex ||
737 glslangIntermediate->getStage() == EShLangTessControl ||
738 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800739
John Kessenich8317e6c2019-08-18 23:58:08 -0600740 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600741 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800742 }
John Kessenich78a45572016-07-08 14:05:15 -0600743 return spv::BuiltInLayer;
744
John Kessenichda581a22015-10-14 14:10:30 -0600745 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600746 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800747 builder.addCapability(spv::CapabilityDrawParameters);
748 return spv::BuiltInBaseVertex;
749
John Kessenichda581a22015-10-14 14:10:30 -0600750 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600751 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800752 builder.addCapability(spv::CapabilityDrawParameters);
753 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200754
John Kessenichda581a22015-10-14 14:10:30 -0600755 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600756 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800757 builder.addCapability(spv::CapabilityDrawParameters);
758 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200759
760 case glslang::EbvPrimitiveId:
761 if (glslangIntermediate->getStage() == EShLangFragment)
762 builder.addCapability(spv::CapabilityGeometry);
763 return spv::BuiltInPrimitiveId;
764
Rex Xu37cdcee2017-06-29 17:46:34 +0800765 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800766 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
767 builder.addCapability(spv::CapabilityStencilExportEXT);
768 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800769
John Kessenich140f3df2015-06-26 16:58:36 -0600770 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600771 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
772 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
773 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
774 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600775 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800776
Rex Xu574ab042016-04-14 16:53:07 +0800777 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800778 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800779 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
780 return spv::BuiltInSubgroupSize;
781
Rex Xu574ab042016-04-14 16:53:07 +0800782 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800783 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800784 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
785 return spv::BuiltInSubgroupLocalInvocationId;
786
Rex Xu574ab042016-04-14 16:53:07 +0800787 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800788 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
789 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600790 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800791
Rex Xu574ab042016-04-14 16:53:07 +0800792 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800793 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
794 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600795 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800796
Rex Xu574ab042016-04-14 16:53:07 +0800797 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800798 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
799 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600800 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800801
Rex Xu574ab042016-04-14 16:53:07 +0800802 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800803 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
804 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600805 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800806
Rex Xu574ab042016-04-14 16:53:07 +0800807 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800808 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
809 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600810 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800811
John Kessenich66011cb2018-03-06 16:12:04 -0700812 case glslang::EbvNumSubgroups:
813 builder.addCapability(spv::CapabilityGroupNonUniform);
814 return spv::BuiltInNumSubgroups;
815
816 case glslang::EbvSubgroupID:
817 builder.addCapability(spv::CapabilityGroupNonUniform);
818 return spv::BuiltInSubgroupId;
819
820 case glslang::EbvSubgroupSize2:
821 builder.addCapability(spv::CapabilityGroupNonUniform);
822 return spv::BuiltInSubgroupSize;
823
824 case glslang::EbvSubgroupInvocation2:
825 builder.addCapability(spv::CapabilityGroupNonUniform);
826 return spv::BuiltInSubgroupLocalInvocationId;
827
828 case glslang::EbvSubgroupEqMask2:
829 builder.addCapability(spv::CapabilityGroupNonUniform);
830 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
831 return spv::BuiltInSubgroupEqMask;
832
833 case glslang::EbvSubgroupGeMask2:
834 builder.addCapability(spv::CapabilityGroupNonUniform);
835 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
836 return spv::BuiltInSubgroupGeMask;
837
838 case glslang::EbvSubgroupGtMask2:
839 builder.addCapability(spv::CapabilityGroupNonUniform);
840 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
841 return spv::BuiltInSubgroupGtMask;
842
843 case glslang::EbvSubgroupLeMask2:
844 builder.addCapability(spv::CapabilityGroupNonUniform);
845 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
846 return spv::BuiltInSubgroupLeMask;
847
848 case glslang::EbvSubgroupLtMask2:
849 builder.addCapability(spv::CapabilityGroupNonUniform);
850 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
851 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600852
Rex Xu17ff3432016-10-14 17:41:45 +0800853 case glslang::EbvBaryCoordNoPersp:
854 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
855 return spv::BuiltInBaryCoordNoPerspAMD;
856
857 case glslang::EbvBaryCoordNoPerspCentroid:
858 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
859 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
860
861 case glslang::EbvBaryCoordNoPerspSample:
862 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
863 return spv::BuiltInBaryCoordNoPerspSampleAMD;
864
865 case glslang::EbvBaryCoordSmooth:
866 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
867 return spv::BuiltInBaryCoordSmoothAMD;
868
869 case glslang::EbvBaryCoordSmoothCentroid:
870 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
871 return spv::BuiltInBaryCoordSmoothCentroidAMD;
872
873 case glslang::EbvBaryCoordSmoothSample:
874 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
875 return spv::BuiltInBaryCoordSmoothSampleAMD;
876
877 case glslang::EbvBaryCoordPullModel:
878 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
879 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800880
John Kessenich6c8aaac2017-02-27 01:20:51 -0700881 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600882 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700883 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700884 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700885
886 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600887 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700888 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700889 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700890
Daniel Koch5154db52018-11-26 10:01:58 -0500891 case glslang::EbvFragSizeEXT:
892 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
893 builder.addCapability(spv::CapabilityFragmentDensityEXT);
894 return spv::BuiltInFragSizeEXT;
895
896 case glslang::EbvFragInvocationCountEXT:
897 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
898 builder.addCapability(spv::CapabilityFragmentDensityEXT);
899 return spv::BuiltInFragInvocationCountEXT;
900
chaoc771d89f2017-01-13 01:10:53 -0800901 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800902 if (!memberDeclaration) {
903 builder.addExtension(spv::E_SPV_NV_viewport_array2);
904 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
905 }
chaoc771d89f2017-01-13 01:10:53 -0800906 return spv::BuiltInViewportMaskNV;
907 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800908 if (!memberDeclaration) {
909 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
910 builder.addCapability(spv::CapabilityShaderStereoViewNV);
911 }
chaoc771d89f2017-01-13 01:10:53 -0800912 return spv::BuiltInSecondaryPositionNV;
913 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800914 if (!memberDeclaration) {
915 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
916 builder.addCapability(spv::CapabilityShaderStereoViewNV);
917 }
chaoc771d89f2017-01-13 01:10:53 -0800918 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800919 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800920 if (!memberDeclaration) {
921 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
922 builder.addCapability(spv::CapabilityPerViewAttributesNV);
923 }
chaocdf3956c2017-02-14 14:52:34 -0800924 return spv::BuiltInPositionPerViewNV;
925 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800926 if (!memberDeclaration) {
927 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
928 builder.addCapability(spv::CapabilityPerViewAttributesNV);
929 }
chaocdf3956c2017-02-14 14:52:34 -0800930 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700931 case glslang::EbvFragFullyCoveredNV:
932 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
933 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
934 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700935 case glslang::EbvFragmentSizeNV:
936 builder.addExtension(spv::E_SPV_NV_shading_rate);
937 builder.addCapability(spv::CapabilityShadingRateNV);
938 return spv::BuiltInFragmentSizeNV;
939 case glslang::EbvInvocationsPerPixelNV:
940 builder.addExtension(spv::E_SPV_NV_shading_rate);
941 builder.addCapability(spv::CapabilityShadingRateNV);
942 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700943
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400945 case glslang::EbvLaunchId:
946 return spv::BuiltInLaunchIdKHR;
947 case glslang::EbvLaunchSize:
948 return spv::BuiltInLaunchSizeKHR;
949 case glslang::EbvWorldRayOrigin:
950 return spv::BuiltInWorldRayOriginKHR;
951 case glslang::EbvWorldRayDirection:
952 return spv::BuiltInWorldRayDirectionKHR;
953 case glslang::EbvObjectRayOrigin:
954 return spv::BuiltInObjectRayOriginKHR;
955 case glslang::EbvObjectRayDirection:
956 return spv::BuiltInObjectRayDirectionKHR;
957 case glslang::EbvRayTmin:
958 return spv::BuiltInRayTminKHR;
959 case glslang::EbvRayTmax:
960 return spv::BuiltInRayTmaxKHR;
961 case glslang::EbvInstanceCustomIndex:
962 return spv::BuiltInInstanceCustomIndexKHR;
963 case glslang::EbvHitT:
964 return spv::BuiltInHitTKHR;
965 case glslang::EbvHitKind:
966 return spv::BuiltInHitKindKHR;
967 case glslang::EbvObjectToWorld:
968 case glslang::EbvObjectToWorld3x4:
969 return spv::BuiltInObjectToWorldKHR;
970 case glslang::EbvWorldToObject:
971 case glslang::EbvWorldToObject3x4:
972 return spv::BuiltInWorldToObjectKHR;
973 case glslang::EbvIncomingRayFlags:
974 return spv::BuiltInIncomingRayFlagsKHR;
975 case glslang::EbvGeometryIndex:
976 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400977
978 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700979 case glslang::EbvBaryCoordNV:
980 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
981 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
982 return spv::BuiltInBaryCoordNV;
983 case glslang::EbvBaryCoordNoPerspNV:
984 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
985 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
986 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400987
988 // mesh shaders
989 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700990 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400991 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700992 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400993 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700994 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400995 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700996 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400997 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700998 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001000 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001001 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001003 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001004 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001005
1006 // sm builtins
1007 case glslang::EbvWarpsPerSM:
1008 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1009 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1010 return spv::BuiltInWarpsPerSMNV;
1011 case glslang::EbvSMCount:
1012 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1013 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1014 return spv::BuiltInSMCountNV;
1015 case glslang::EbvWarpID:
1016 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1017 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1018 return spv::BuiltInWarpIDNV;
1019 case glslang::EbvSMID:
1020 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1021 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1022 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001023#endif
1024
Rex Xu3e783f92017-02-22 16:44:48 +08001025 default:
1026 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001027 }
1028}
1029
Rex Xufc618912015-09-09 16:42:49 +08001030// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001031spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001032{
1033 assert(type.getBasicType() == glslang::EbtSampler);
1034
John Kessenichb9197c82019-08-11 07:41:45 -06001035#ifdef GLSLANG_WEB
1036 return spv::ImageFormatUnknown;
1037#endif
1038
John Kessenich5d0fa972016-02-15 11:57:00 -07001039 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001040 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001041 case glslang::ElfRg32f:
1042 case glslang::ElfRg16f:
1043 case glslang::ElfR11fG11fB10f:
1044 case glslang::ElfR16f:
1045 case glslang::ElfRgba16:
1046 case glslang::ElfRgb10A2:
1047 case glslang::ElfRg16:
1048 case glslang::ElfRg8:
1049 case glslang::ElfR16:
1050 case glslang::ElfR8:
1051 case glslang::ElfRgba16Snorm:
1052 case glslang::ElfRg16Snorm:
1053 case glslang::ElfRg8Snorm:
1054 case glslang::ElfR16Snorm:
1055 case glslang::ElfR8Snorm:
1056
1057 case glslang::ElfRg32i:
1058 case glslang::ElfRg16i:
1059 case glslang::ElfRg8i:
1060 case glslang::ElfR16i:
1061 case glslang::ElfR8i:
1062
1063 case glslang::ElfRgb10a2ui:
1064 case glslang::ElfRg32ui:
1065 case glslang::ElfRg16ui:
1066 case glslang::ElfRg8ui:
1067 case glslang::ElfR16ui:
1068 case glslang::ElfR8ui:
1069 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1070 break;
1071
1072 default:
1073 break;
1074 }
1075
1076 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001077 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001078 case glslang::ElfNone: return spv::ImageFormatUnknown;
1079 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1080 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1081 case glslang::ElfR32f: return spv::ImageFormatR32f;
1082 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1083 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1084 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1085 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1086 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1087 case glslang::ElfR16f: return spv::ImageFormatR16f;
1088 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1089 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1090 case glslang::ElfRg16: return spv::ImageFormatRg16;
1091 case glslang::ElfRg8: return spv::ImageFormatRg8;
1092 case glslang::ElfR16: return spv::ImageFormatR16;
1093 case glslang::ElfR8: return spv::ImageFormatR8;
1094 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1095 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1096 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1097 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1098 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1099 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1100 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1101 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1102 case glslang::ElfR32i: return spv::ImageFormatR32i;
1103 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1104 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1105 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1106 case glslang::ElfR16i: return spv::ImageFormatR16i;
1107 case glslang::ElfR8i: return spv::ImageFormatR8i;
1108 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1109 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1110 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1111 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1112 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1113 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1114 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1115 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1116 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1117 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001118 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001119 }
1120}
1121
John Kessenich8985fc92020-03-03 10:25:07 -07001122spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1123 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001124{
John Kesseniche18fd202018-01-30 11:01:39 -07001125 if (selectionNode.getFlatten())
1126 return spv::SelectionControlFlattenMask;
1127 if (selectionNode.getDontFlatten())
1128 return spv::SelectionControlDontFlattenMask;
1129 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001130}
1131
John Kessenich8985fc92020-03-03 10:25:07 -07001132spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1133 const
steve-lunargf1709e72017-05-02 20:14:50 -06001134{
John Kesseniche18fd202018-01-30 11:01:39 -07001135 if (switchNode.getFlatten())
1136 return spv::SelectionControlFlattenMask;
1137 if (switchNode.getDontFlatten())
1138 return spv::SelectionControlDontFlattenMask;
1139 return spv::SelectionControlMaskNone;
1140}
1141
John Kessenicha2858d92018-01-31 08:11:18 -07001142// return a non-0 dependency if the dependency argument must be set
1143spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001144 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001145{
1146 spv::LoopControlMask control = spv::LoopControlMaskNone;
1147
1148 if (loopNode.getDontUnroll())
1149 control = control | spv::LoopControlDontUnrollMask;
1150 if (loopNode.getUnroll())
1151 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001152 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001153 control = control | spv::LoopControlDependencyInfiniteMask;
1154 else if (loopNode.getLoopDependency() > 0) {
1155 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001156 operands.push_back((unsigned int)loopNode.getLoopDependency());
1157 }
1158 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1159 if (loopNode.getMinIterations() > 0) {
1160 control = control | spv::LoopControlMinIterationsMask;
1161 operands.push_back(loopNode.getMinIterations());
1162 }
1163 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1164 control = control | spv::LoopControlMaxIterationsMask;
1165 operands.push_back(loopNode.getMaxIterations());
1166 }
1167 if (loopNode.getIterationMultiple() > 1) {
1168 control = control | spv::LoopControlIterationMultipleMask;
1169 operands.push_back(loopNode.getIterationMultiple());
1170 }
1171 if (loopNode.getPeelCount() > 0) {
1172 control = control | spv::LoopControlPeelCountMask;
1173 operands.push_back(loopNode.getPeelCount());
1174 }
1175 if (loopNode.getPartialCount() > 0) {
1176 control = control | spv::LoopControlPartialCountMask;
1177 operands.push_back(loopNode.getPartialCount());
1178 }
John Kessenicha2858d92018-01-31 08:11:18 -07001179 }
John Kesseniche18fd202018-01-30 11:01:39 -07001180
1181 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001182}
1183
John Kessenicha5c5fb62017-05-05 05:09:58 -06001184// Translate glslang type to SPIR-V storage class.
1185spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1186{
Torosdagli06c2eee2020-03-19 11:09:57 -04001187 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001188 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001189 if (type.getQualifier().isPipeInput())
1190 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001191 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001192 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001193
1194 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001195 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001196 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001197 return spv::StorageClassAtomicCounter;
1198 if (type.containsOpaque())
1199 return spv::StorageClassUniformConstant;
1200 }
1201
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001202 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001203 type.getQualifier().isShaderRecord()) {
1204 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001205 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001206
John Kessenichbed4e4f2017-09-08 02:38:07 -06001207 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001208 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001209 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001210 }
1211
1212 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001213 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001214 return spv::StorageClassPushConstant;
1215 if (type.getBasicType() == glslang::EbtBlock)
1216 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001217 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001218 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001219
1220 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001221 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1222 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1223 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001224 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001225#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001226 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1227 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1228 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1229 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1230 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001231#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001232 default:
1233 assert(0);
1234 break;
1235 }
1236
1237 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001238}
1239
John Kessenich5611c6d2018-04-05 11:25:02 -06001240// Add capabilities pertaining to how an array is indexed.
1241void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1242 const glslang::TType& indexType)
1243{
John Kessenichb9197c82019-08-11 07:41:45 -06001244#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001245 if (indexType.getQualifier().isNonUniform()) {
1246 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001247 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001248 if (baseType.getBasicType() == glslang::EbtSampler) {
1249 if (baseType.getQualifier().hasAttachment())
1250 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001251 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001252 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001253 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001254 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1255 else if (baseType.isImage())
1256 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1257 else if (baseType.isTexture())
1258 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1259 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1260 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1261 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1262 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1263 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1264 }
1265 } else {
1266 // assume a dynamically uniform index
1267 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001268 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001269 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001270 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001271 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001272 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001273 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001274 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001275 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001276 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001277 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001278 }
1279 }
John Kessenichb9197c82019-08-11 07:41:45 -06001280#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001281}
1282
qining25262b32016-05-06 17:25:16 -04001283// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001284// descriptor set.
1285bool IsDescriptorResource(const glslang::TType& type)
1286{
John Kessenichf7497e22016-03-08 21:36:22 -07001287 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001288 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001289 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001290 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001291 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001292
1293 // non block...
1294 // basically samplerXXX/subpass/sampler/texture are all included
1295 // if they are the global-scope-class, not the function parameter
1296 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001297 if (type.getBasicType() == glslang::EbtSampler ||
1298 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001299 return type.getQualifier().isUniformOrBuffer();
1300
1301 // None of the above.
1302 return false;
1303}
1304
John Kesseniche0b6cad2015-12-24 10:30:13 -07001305void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1306{
1307 if (child.layoutMatrix == glslang::ElmNone)
1308 child.layoutMatrix = parent.layoutMatrix;
1309
1310 if (parent.invariant)
1311 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001312 if (parent.flat)
1313 child.flat = true;
1314 if (parent.centroid)
1315 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001316#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001317 if (parent.nopersp)
1318 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001319 if (parent.explicitInterp)
1320 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001321 if (parent.perPrimitiveNV)
1322 child.perPrimitiveNV = true;
1323 if (parent.perViewNV)
1324 child.perViewNV = true;
1325 if (parent.perTaskNV)
1326 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001327 if (parent.patch)
1328 child.patch = true;
1329 if (parent.sample)
1330 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001331 if (parent.coherent)
1332 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001333 if (parent.devicecoherent)
1334 child.devicecoherent = true;
1335 if (parent.queuefamilycoherent)
1336 child.queuefamilycoherent = true;
1337 if (parent.workgroupcoherent)
1338 child.workgroupcoherent = true;
1339 if (parent.subgroupcoherent)
1340 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001341 if (parent.shadercallcoherent)
1342 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001343 if (parent.nonprivate)
1344 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001345 if (parent.volatil)
1346 child.volatil = true;
1347 if (parent.restrict)
1348 child.restrict = true;
1349 if (parent.readonly)
1350 child.readonly = true;
1351 if (parent.writeonly)
1352 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001353#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001354}
1355
John Kessenichf2b7f332016-09-01 17:05:23 -06001356bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001357{
John Kessenich7b9fa252016-01-21 18:56:57 -07001358 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001359 // - struct members might inherit from a struct declaration
1360 // (note that non-block structs don't explicitly inherit,
1361 // only implicitly, meaning no decoration involved)
1362 // - affect decorations on the struct members
1363 // (note smooth does not, and expecting something like volatile
1364 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001365 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001366 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001367}
1368
John Kessenich140f3df2015-06-26 16:58:36 -06001369//
1370// Implement the TGlslangToSpvTraverser class.
1371//
1372
John Kessenich8985fc92020-03-03 10:25:07 -07001373TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1374 const glslang::TIntermediate* glslangIntermediate,
1375 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1376 TIntermTraverser(true, false, true),
1377 options(options),
1378 shaderEntry(nullptr), currentFunction(nullptr),
1379 sequenceDepth(0), logger(buildLogger),
1380 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1381 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1382 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001383 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1384 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001385{
1386 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1387
1388 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001389 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1390 glslangIntermediate->getVersion());
1391
John Kessenich121853f2017-05-31 17:11:16 -06001392 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001393 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001394 builder.setSourceFile(glslangIntermediate->getSourceFile());
1395
1396 // Set the source shader's text. If for SPV version 1.0, include
1397 // a preamble in comments stating the OpModuleProcessed instructions.
1398 // Otherwise, emit those as actual instructions.
1399 std::string text;
1400 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1401 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001402 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001403 text.append("// OpModuleProcessed ");
1404 text.append(processes[p]);
1405 text.append("\n");
1406 } else
1407 builder.addModuleProcessed(processes[p]);
1408 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001409 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001410 text.append("#line 1\n");
1411 text.append(glslangIntermediate->getSourceText());
1412 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001413 // Pass name and text for all included files
1414 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1415 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1416 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001417 }
John Kessenich140f3df2015-06-26 16:58:36 -06001418 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001419
1420 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1421 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1422
1423 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1424 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001425 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001426 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001427 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001428 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001429 memoryModel = spv::MemoryModelVulkanKHR;
1430 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001431 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001432 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001433 builder.setMemoryModel(addressingModel, memoryModel);
1434
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001435 if (glslangIntermediate->usingVariablePointers()) {
1436 builder.addCapability(spv::CapabilityVariablePointers);
1437 }
1438
John Kessenicheee9d532016-09-19 18:09:30 -06001439 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1440 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001441
1442 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001443 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1444 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
Pankaj Mistry2a8ead22020-04-26 17:52:31 -07001445 builder.addSourceExtension(it->first.c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001446
1447 // Add the top-level modes for this shader.
1448
John Kessenich92187592016-02-01 13:45:25 -07001449 if (glslangIntermediate->getXfbMode()) {
1450 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001451 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001452 }
John Kessenich140f3df2015-06-26 16:58:36 -06001453
alelenv59216d52020-05-21 04:38:41 -07001454 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001455 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1456 }
1457
John Kessenich140f3df2015-06-26 16:58:36 -06001458 unsigned int mode;
1459 switch (glslangIntermediate->getStage()) {
1460 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001461 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001462 break;
1463
John Kessenicha28f7a72019-08-06 07:00:58 -06001464 case EShLangFragment:
1465 builder.addCapability(spv::CapabilityShader);
1466 if (glslangIntermediate->getPixelCenterInteger())
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1468
1469 if (glslangIntermediate->getOriginUpperLeft())
1470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1471 else
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1473
1474 if (glslangIntermediate->getEarlyFragmentTests())
1475 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1476
1477 if (glslangIntermediate->getPostDepthCoverage()) {
1478 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1479 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1480 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1481 }
1482
John Kessenichb9197c82019-08-11 07:41:45 -06001483 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1484 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1485
1486#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001487
John Kessenicha28f7a72019-08-06 07:00:58 -06001488 switch(glslangIntermediate->getDepth()) {
1489 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1490 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1491 default: mode = spv::ExecutionModeMax; break;
1492 }
1493 if (mode != spv::ExecutionModeMax)
1494 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001495 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001496 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1497 break;
1498 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1499 break;
1500 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1501 break;
1502 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1503 break;
1504 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1505 break;
1506 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1507 break;
1508 default: mode = spv::ExecutionModeMax;
1509 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001510 }
1511 if (mode != spv::ExecutionModeMax) {
1512 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1513 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1514 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1515 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1516 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1517 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1518 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1519 } else {
1520 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1521 }
1522 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1523 }
John Kessenichb9197c82019-08-11 07:41:45 -06001524#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001525 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001526
John Kessenicha28f7a72019-08-06 07:00:58 -06001527 case EShLangCompute:
1528 builder.addCapability(spv::CapabilityShader);
1529 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1530 glslangIntermediate->getLocalSize(1),
1531 glslangIntermediate->getLocalSize(2));
1532 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1533 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1534 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1535 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1536 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1537 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1538 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1539 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1540 }
1541 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001542#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001543 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001544 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001545 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001546
steve-lunarge7412492017-03-23 11:56:07 -06001547 glslang::TLayoutGeometry primitive;
1548
1549 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001550 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1551 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001552 primitive = glslangIntermediate->getOutputPrimitive();
1553 } else {
1554 primitive = glslangIntermediate->getInputPrimitive();
1555 }
1556
1557 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001558 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1559 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1560 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001561 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001562 }
John Kessenich4016e382016-07-15 11:53:56 -06001563 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001564 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1565
John Kesseniche6903322015-10-13 16:29:02 -06001566 switch (glslangIntermediate->getVertexSpacing()) {
1567 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1568 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1569 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001570 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001571 }
John Kessenich4016e382016-07-15 11:53:56 -06001572 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001573 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1574
1575 switch (glslangIntermediate->getVertexOrder()) {
1576 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1577 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001578 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001579 }
John Kessenich4016e382016-07-15 11:53:56 -06001580 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001581 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1582
1583 if (glslangIntermediate->getPointMode())
1584 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001585 break;
1586
1587 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001588 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001589 switch (glslangIntermediate->getInputPrimitive()) {
1590 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1591 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1592 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001593 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001594 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001595 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001596 }
John Kessenich4016e382016-07-15 11:53:56 -06001597 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001598 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001599
John Kessenich140f3df2015-06-26 16:58:36 -06001600 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1601
1602 switch (glslangIntermediate->getOutputPrimitive()) {
1603 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1604 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1605 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001606 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001607 }
John Kessenich4016e382016-07-15 11:53:56 -06001608 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001609 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1610 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1611 break;
1612
Daniel Kochdb32b242020-03-17 20:42:47 -04001613 case EShLangRayGen:
1614 case EShLangIntersect:
1615 case EShLangAnyHit:
1616 case EShLangClosestHit:
1617 case EShLangMiss:
1618 case EShLangCallable:
1619 {
1620 auto& extensions = glslangIntermediate->getRequestedExtensions();
1621 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1622 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1623 builder.addExtension("SPV_KHR_ray_tracing");
1624 }
1625 else {
1626 builder.addCapability(spv::CapabilityRayTracingNV);
1627 builder.addExtension("SPV_NV_ray_tracing");
1628 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001629 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001630 }
Chao Chen3c366992018-09-19 11:41:59 -07001631 case EShLangTaskNV:
1632 case EShLangMeshNV:
1633 builder.addCapability(spv::CapabilityMeshShadingNV);
1634 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1635 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1636 glslangIntermediate->getLocalSize(1),
1637 glslangIntermediate->getLocalSize(2));
1638 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001639 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1640 glslangIntermediate->getVertices());
1641 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1642 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001643
1644 switch (glslangIntermediate->getOutputPrimitive()) {
1645 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1646 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1647 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1648 default: mode = spv::ExecutionModeMax; break;
1649 }
1650 if (mode != spv::ExecutionModeMax)
1651 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1652 }
1653 break;
1654#endif
1655
John Kessenich140f3df2015-06-26 16:58:36 -06001656 default:
1657 break;
1658 }
John Kessenich140f3df2015-06-26 16:58:36 -06001659}
1660
John Kessenichfca82622016-11-26 13:23:20 -07001661// Finish creating SPV, after the traversal is complete.
1662void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001663{
John Kessenichf04c51b2018-08-03 15:56:12 -06001664 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001665 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001666 builder.setBuildPoint(shaderEntry->getLastBlock());
1667 builder.leaveFunction();
1668 }
1669
John Kessenich7ba63412015-12-20 17:37:07 -07001670 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001671 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1672 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001673
David Neto8c3d5b42019-10-21 14:50:31 -04001674 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001675 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001676 // Note: WebGPU code generation must have the opportunity to aggressively
1677 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001678 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001679}
1680
John Kessenichfca82622016-11-26 13:23:20 -07001681// Write the SPV into 'out'.
1682void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001683{
John Kessenichfca82622016-11-26 13:23:20 -07001684 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001685}
1686
1687//
1688// Implement the traversal functions.
1689//
1690// Return true from interior nodes to have the external traversal
1691// continue on to children. Return false if children were
1692// already processed.
1693//
1694
1695//
qining25262b32016-05-06 17:25:16 -04001696// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001697// - uniform/input reads
1698// - output writes
1699// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1700// - something simple that degenerates into the last bullet
1701//
1702void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1703{
qining75d1d802016-04-06 14:42:01 -04001704 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001705 if (symbol->getType().isStruct())
1706 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1707
qining75d1d802016-04-06 14:42:01 -04001708 if (symbol->getType().getQualifier().isSpecConstant())
1709 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1710
John Kessenich140f3df2015-06-26 16:58:36 -06001711 // getSymbolId() will set up all the IO decorations on the first call.
1712 // Formal function parameters were mapped during makeFunctions().
1713 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001714
John Kessenich7ba63412015-12-20 17:37:07 -07001715 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001716 if (!symbol->getType().getQualifier().isParamInput() &&
1717 !symbol->getType().getQualifier().isParamOutput()) {
1718 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1719 // Consider adding to the OpEntryPoint interface list.
1720 // Only looking at structures if they have at least one member.
1721 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1722 spv::StorageClass sc = builder.getStorageClass(id);
1723 // Before SPIR-V 1.4, we only want to include Input and Output.
1724 // Starting with SPIR-V 1.4, we want all globals.
1725 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1726 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1727 iOSet.insert(id);
1728 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001729 }
John Kessenich5f77d862017-09-19 11:09:59 -06001730 }
John Kessenich9c14f772019-06-17 08:38:35 -06001731
Daniel Kochdb32b242020-03-17 20:42:47 -04001732 // If the SPIR-V type is required to be different than the AST type
1733 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001734 // translate now from the SPIR-V type to the AST type, for the consuming
1735 // operation.
1736 // Note this turns it from an l-value to an r-value.
1737 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1738 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1739 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001740 }
1741
1742 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001743 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001744 // Prepare to generate code for the access
1745
1746 // L-value chains will be computed left to right. We're on the symbol now,
1747 // which is the left-most part of the access chain, so now is "clear" time,
1748 // followed by setting the base.
1749 builder.clearAccessChain();
1750
1751 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001752 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001753 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001754 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001755 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001756 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001757 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001758 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001759 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1760 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001761 builder.setAccessChainRValue(id);
1762 else
1763 builder.setAccessChainLValue(id);
1764 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001765
John Kessenichb9197c82019-08-11 07:41:45 -06001766#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001767 // Process linkage-only nodes for any special additional interface work.
1768 if (linkageOnly) {
1769 if (glslangIntermediate->getHlslFunctionality1()) {
1770 // Map implicit counter buffers to their originating buffers, which should have been
1771 // seen by now, given earlier pruning of unused counters, and preservation of order
1772 // of declaration.
1773 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1774 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1775 // Save possible originating buffers for counter buffers, keyed by
1776 // making the potential counter-buffer name.
1777 std::string keyName = symbol->getName().c_str();
1778 keyName = glslangIntermediate->addCounterBufferName(keyName);
1779 counterOriginator[keyName] = symbol;
1780 } else {
1781 // Handle a counter buffer, by finding the saved originating buffer.
1782 std::string keyName = symbol->getName().c_str();
1783 auto it = counterOriginator.find(keyName);
1784 if (it != counterOriginator.end()) {
1785 id = getSymbolId(it->second);
1786 if (id != spv::NoResult) {
1787 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001788 if (counterId != spv::NoResult) {
1789 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001790 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001791 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001792 }
1793 }
1794 }
1795 }
1796 }
1797 }
John Kessenich155d3512019-08-08 23:29:20 -06001798#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001799}
1800
1801bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1802{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001803 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001804 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1805 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1806 }
1807 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1808 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1809 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001810
qining40887662016-04-03 22:20:42 -04001811 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1812 if (node->getType().getQualifier().isSpecConstant())
1813 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1814
John Kessenich140f3df2015-06-26 16:58:36 -06001815 // First, handle special cases
1816 switch (node->getOp()) {
1817 case glslang::EOpAssign:
1818 case glslang::EOpAddAssign:
1819 case glslang::EOpSubAssign:
1820 case glslang::EOpMulAssign:
1821 case glslang::EOpVectorTimesMatrixAssign:
1822 case glslang::EOpVectorTimesScalarAssign:
1823 case glslang::EOpMatrixTimesScalarAssign:
1824 case glslang::EOpMatrixTimesMatrixAssign:
1825 case glslang::EOpDivAssign:
1826 case glslang::EOpModAssign:
1827 case glslang::EOpAndAssign:
1828 case glslang::EOpInclusiveOrAssign:
1829 case glslang::EOpExclusiveOrAssign:
1830 case glslang::EOpLeftShiftAssign:
1831 case glslang::EOpRightShiftAssign:
1832 // A bin-op assign "a += b" means the same thing as "a = a + b"
1833 // where a is evaluated before b. For a simple assignment, GLSL
1834 // says to evaluate the left before the right. So, always, left
1835 // node then right node.
1836 {
1837 // get the left l-value, save it away
1838 builder.clearAccessChain();
1839 node->getLeft()->traverse(this);
1840 spv::Builder::AccessChain lValue = builder.getAccessChain();
1841
1842 // evaluate the right
1843 builder.clearAccessChain();
1844 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001845 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001846
1847 if (node->getOp() != glslang::EOpAssign) {
1848 // the left is also an r-value
1849 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001850 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001851
1852 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001853 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001854 TranslateNoContractionDecoration(node->getType().getQualifier()),
1855 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001856 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001857 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1858 node->getType().getBasicType());
1859
1860 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001861 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001862 }
1863
1864 // store the result
1865 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001866 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001867
1868 // assignments are expressions having an rValue after they are evaluated...
1869 builder.clearAccessChain();
1870 builder.setAccessChainRValue(rValue);
1871 }
1872 return false;
1873 case glslang::EOpIndexDirect:
1874 case glslang::EOpIndexDirectStruct:
1875 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001876 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001877 // Get the left part of the access chain.
1878 node->getLeft()->traverse(this);
1879
1880 // Add the next element in the chain
1881
David Netoa901ffe2016-06-08 14:11:40 +01001882 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001883 if (! node->getLeft()->getType().isArray() &&
1884 node->getLeft()->getType().isVector() &&
1885 node->getOp() == glslang::EOpIndexDirect) {
1886 // This is essentially a hard-coded vector swizzle of size 1,
1887 // so short circuit the access-chain stuff with a swizzle.
1888 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001889 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001890 int dummySize;
1891 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1892 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001893 glslangIntermediate->getBaseAlignmentScalar(
1894 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001895 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001896
1897 // Load through a block reference is performed with a dot operator that
1898 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1899 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001900 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001901 !node->getLeft()->getType().isArray() &&
1902 node->getOp() == glslang::EOpIndexDirectStruct)
1903 {
1904 spv::Id left = accessChainLoad(node->getLeft()->getType());
1905 builder.clearAccessChain();
1906 builder.setAccessChainLValue(left);
1907 }
1908
David Netoa901ffe2016-06-08 14:11:40 +01001909 int spvIndex = glslangIndex;
1910 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1911 node->getOp() == glslang::EOpIndexDirectStruct)
1912 {
1913 // This may be, e.g., an anonymous block-member selection, which generally need
1914 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001915 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1916 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1917 std::vector<int>& remapper = memberRemapper[glslangId];
1918 assert(remapper.size() > 0);
1919 spvIndex = remapper[glslangIndex];
1920 }
David Netoa901ffe2016-06-08 14:11:40 +01001921 }
John Kessenichebb50532016-05-16 19:22:05 -06001922
David Netoa901ffe2016-06-08 14:11:40 +01001923 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001924 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1925 TranslateCoherent(node->getLeft()->getType()),
1926 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001927
1928 // Add capabilities here for accessing PointSize and clip/cull distance.
1929 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001930 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001931 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001932 }
1933 }
1934 return false;
1935 case glslang::EOpIndexIndirect:
1936 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001937 // Array, matrix, or vector indirection with variable index.
1938 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001939 // matrices are arrays of vectors, so will also work for a matrix.
1940 // Will use the access chain's 'component' for variable index into a vector.
1941
1942 // This adapter is building access chains left to right.
1943 // Set up the access chain to the left.
1944 node->getLeft()->traverse(this);
1945
1946 // save it so that computing the right side doesn't trash it
1947 spv::Builder::AccessChain partial = builder.getAccessChain();
1948
1949 // compute the next index in the chain
1950 builder.clearAccessChain();
1951 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001952 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001953
John Kessenich5611c6d2018-04-05 11:25:02 -06001954 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1955
John Kessenich140f3df2015-06-26 16:58:36 -06001956 // restore the saved access chain
1957 builder.setAccessChain(partial);
1958
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001959 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1960 int dummySize;
1961 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1962 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001963 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1964 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001965 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001966 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1967 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001968 }
1969 return false;
1970 case glslang::EOpVectorSwizzle:
1971 {
1972 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001973 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001974 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001975 int dummySize;
1976 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1977 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001978 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1979 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001980 }
1981 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001982 case glslang::EOpMatrixSwizzle:
1983 logger->missingFunctionality("matrix swizzle");
1984 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001985 case glslang::EOpLogicalOr:
1986 case glslang::EOpLogicalAnd:
1987 {
1988
1989 // These may require short circuiting, but can sometimes be done as straight
1990 // binary operations. The right operand must be short circuited if it has
1991 // side effects, and should probably be if it is complex.
1992 if (isTrivial(node->getRight()->getAsTyped()))
1993 break; // handle below as a normal binary operation
1994 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001995 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1996 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001997 builder.clearAccessChain();
1998 builder.setAccessChainRValue(result);
1999 }
2000 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002001 default:
2002 break;
2003 }
2004
2005 // Assume generic binary op...
2006
John Kessenich32cfd492016-02-02 12:37:46 -07002007 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002008 builder.clearAccessChain();
2009 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002010 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002011
John Kessenich32cfd492016-02-02 12:37:46 -07002012 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002013 builder.clearAccessChain();
2014 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002015 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002016
John Kessenich32cfd492016-02-02 12:37:46 -07002017 // get result
John Kessenichead86222018-03-28 18:01:20 -06002018 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002019 TranslateNoContractionDecoration(node->getType().getQualifier()),
2020 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002021 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002022 convertGlslangToSpvType(node->getType()), left, right,
2023 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002024
John Kessenich50e57562015-12-21 21:21:11 -07002025 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002026 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002027 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002028 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002029 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002030 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002031 return false;
2032 }
John Kessenich140f3df2015-06-26 16:58:36 -06002033}
2034
John Kessenich9c14f772019-06-17 08:38:35 -06002035// Figure out what, if any, type changes are needed when accessing a specific built-in.
2036// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2037// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002038std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002039 const glslang::TType& glslangType)
2040{
Daniel Kochdb32b242020-03-17 20:42:47 -04002041 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002042 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002043 case glslang::EbvSubGroupEqMask:
2044 case glslang::EbvSubGroupGeMask:
2045 case glslang::EbvSubGroupGtMask:
2046 case glslang::EbvSubGroupLeMask:
2047 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002048 // these require changing a 64-bit scaler -> a vector of 32-bit components
2049 if (glslangType.isVector())
2050 break;
2051 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2052 builder.makeUintType(64));
2053 return ret;
2054 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002055 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2056 // builtins. During visitBinary we insert a transpose
2057 case glslang::EbvWorldToObject3x4:
2058 case glslang::EbvObjectToWorld3x4: {
2059 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2060 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2061 );
2062 return ret;
2063 }
John Kessenich9c14f772019-06-17 08:38:35 -06002064 default:
2065 break;
2066 }
2067
2068 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2069 return ret;
2070}
2071
2072// For an object previously identified (see getForcedType() and forceType)
2073// as needing type translations, do the translation needed for a load, turning
2074// an L-value into in R-value.
2075spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2076{
2077 const auto forceIt = forceType.find(object);
2078 if (forceIt == forceType.end())
2079 return object;
2080
2081 spv::Id desiredTypeId = forceIt->second;
2082 spv::Id objectTypeId = builder.getTypeId(object);
2083 assert(builder.isPointerType(objectTypeId));
2084 objectTypeId = builder.getContainedTypeId(objectTypeId);
2085 if (builder.isVectorType(objectTypeId) &&
2086 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2087 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2088 // handle 32-bit v.xy* -> 64-bit
2089 builder.clearAccessChain();
2090 builder.setAccessChainLValue(object);
2091 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2092 std::vector<spv::Id> components;
2093 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2094 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2095
2096 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2097 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2098 builder.createCompositeConstruct(vecType, components));
2099 } else {
2100 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2101 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002102 } else if (builder.isMatrixType(objectTypeId)) {
2103 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2104 // and we insert a transpose after loading the original non-transposed builtins
2105 builder.clearAccessChain();
2106 builder.setAccessChainLValue(object);
2107 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2108 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2109
2110 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002111 logger->missingFunctionality("forcing non 32-bit vector type");
2112 }
2113
2114 return object;
2115}
2116
John Kessenich140f3df2015-06-26 16:58:36 -06002117bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2118{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002119 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002120
qining40887662016-04-03 22:20:42 -04002121 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2122 if (node->getType().getQualifier().isSpecConstant())
2123 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2124
John Kessenichfc51d282015-08-19 13:34:18 -06002125 spv::Id result = spv::NoResult;
2126
2127 // try texturing first
2128 result = createImageTextureFunctionCall(node);
2129 if (result != spv::NoResult) {
2130 builder.clearAccessChain();
2131 builder.setAccessChainRValue(result);
2132
2133 return false; // done with this node
2134 }
2135
2136 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002137
2138 if (node->getOp() == glslang::EOpArrayLength) {
2139 // Quite special; won't want to evaluate the operand.
2140
John Kessenich5611c6d2018-04-05 11:25:02 -06002141 // Currently, the front-end does not allow .length() on an array until it is sized,
2142 // except for the last block membeor of an SSBO.
2143 // TODO: If this changes, link-time sized arrays might show up here, and need their
2144 // size extracted.
2145
John Kessenichc9a80832015-09-12 12:17:44 -06002146 // Normal .length() would have been constant folded by the front-end.
2147 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002148 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002149
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002150 spv::Id length;
2151 if (node->getOperand()->getType().isCoopMat()) {
2152 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2153
2154 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2155 assert(builder.isCooperativeMatrixType(typeId));
2156
2157 length = builder.createCooperativeMatrixLength(typeId);
2158 } else {
2159 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2160 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002161 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2162 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002163 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2164 }
John Kessenichc9a80832015-09-12 12:17:44 -06002165
John Kessenich8c869672018-11-28 07:01:37 -07002166 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2167 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2168 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002169 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2170 if (builder.isInSpecConstCodeGenMode()) {
2171 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2172 } else {
2173 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2174 }
2175 }
John Kessenich8c869672018-11-28 07:01:37 -07002176
John Kessenichc9a80832015-09-12 12:17:44 -06002177 builder.clearAccessChain();
2178 builder.setAccessChainRValue(length);
2179
2180 return false;
2181 }
2182
John Kessenichfc51d282015-08-19 13:34:18 -06002183 // Start by evaluating the operand
2184
John Kessenich8c8505c2016-07-26 12:50:38 -06002185 // Does it need a swizzle inversion? If so, evaluation is inverted;
2186 // operate first on the swizzle base, then apply the swizzle.
2187 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002188 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2189 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002190 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2191 invertedType = getInvertedSwizzleType(*node->getOperand());
2192
John Kessenich140f3df2015-06-26 16:58:36 -06002193 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002194 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002195 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002196 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002197 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002198 operandNode = node->getOperand();
2199
2200 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002201
Rex Xufc618912015-09-09 16:42:49 +08002202 spv::Id operand = spv::NoResult;
2203
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002204 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2205
John Kessenichfb4f2332019-08-09 03:49:15 -06002206#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002207 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2208 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002209 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002210 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2211 node->getOp() == glslang::EOpRayQueryProceed ||
2212 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2213 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2214 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2215 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2216 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2217 node->getOp() == glslang::EOpRayQueryTerminate ||
2218 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002219 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002220 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2221 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2222 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002223#endif
2224 {
John Kessenich32cfd492016-02-02 12:37:46 -07002225 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002226 }
John Kessenich140f3df2015-06-26 16:58:36 -06002227
John Kessenichead86222018-03-28 18:01:20 -06002228 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002229 TranslateNoContractionDecoration(node->getType().getQualifier()),
2230 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002231
2232 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002233 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002234 result = createConversion(node->getOp(), decorations, resultType(), operand,
2235 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002236
2237 // if not, then possibly an operation
2238 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002239 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2240 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002241
2242 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002243 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002244 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002245 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002246 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002247
John Kessenich140f3df2015-06-26 16:58:36 -06002248 builder.clearAccessChain();
2249 builder.setAccessChainRValue(result);
2250
2251 return false; // done with this node
2252 }
2253
2254 // it must be a special case, check...
2255 switch (node->getOp()) {
2256 case glslang::EOpPostIncrement:
2257 case glslang::EOpPostDecrement:
2258 case glslang::EOpPreIncrement:
2259 case glslang::EOpPreDecrement:
2260 {
2261 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002262 spv::Id one = 0;
2263 if (node->getBasicType() == glslang::EbtFloat)
2264 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002265#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002266 else if (node->getBasicType() == glslang::EbtDouble)
2267 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002268 else if (node->getBasicType() == glslang::EbtFloat16)
2269 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002270 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2271 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002272 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2273 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002274 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2275 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002276#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002277 else
2278 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002279 glslang::TOperator op;
2280 if (node->getOp() == glslang::EOpPreIncrement ||
2281 node->getOp() == glslang::EOpPostIncrement)
2282 op = glslang::EOpAdd;
2283 else
2284 op = glslang::EOpSub;
2285
John Kessenichead86222018-03-28 18:01:20 -06002286 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002287 convertGlslangToSpvType(node->getType()), operand, one,
2288 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002289 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002290
2291 // The result of operation is always stored, but conditionally the
2292 // consumed result. The consumed result is always an r-value.
2293 builder.accessChainStore(result);
2294 builder.clearAccessChain();
2295 if (node->getOp() == glslang::EOpPreIncrement ||
2296 node->getOp() == glslang::EOpPreDecrement)
2297 builder.setAccessChainRValue(result);
2298 else
2299 builder.setAccessChainRValue(operand);
2300 }
2301
2302 return false;
2303
John Kessenich155d3512019-08-08 23:29:20 -06002304#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002305 case glslang::EOpEmitStreamVertex:
2306 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2307 return false;
2308 case glslang::EOpEndStreamPrimitive:
2309 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2310 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002311 case glslang::EOpRayQueryTerminate:
2312 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2313 return false;
2314 case glslang::EOpRayQueryConfirmIntersection:
2315 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2316 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002317#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002318
2319 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002320 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002321 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002322 }
John Kessenich140f3df2015-06-26 16:58:36 -06002323}
2324
Jeff Bolz53134492019-06-25 13:31:10 -05002325// Construct a composite object, recursively copying members if their types don't match
2326spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2327{
2328 for (int c = 0; c < (int)constituents.size(); ++c) {
2329 spv::Id& constituent = constituents[c];
2330 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2331 spv::Id rType = builder.getTypeId(constituent);
2332 if (lType != rType) {
2333 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2334 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2335 } else if (builder.isStructType(rType)) {
2336 std::vector<spv::Id> rTypeConstituents;
2337 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2338 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002339 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2340 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002341 }
2342 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2343 } else {
2344 assert(builder.isArrayType(rType));
2345 std::vector<spv::Id> rTypeConstituents;
2346 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2347
2348 spv::Id elementRType = builder.getContainedTypeId(rType);
2349 for (int i = 0; i < numrTypeConstituents; ++i) {
2350 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2351 }
2352 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2353 }
2354 }
2355 }
2356 return builder.createCompositeConstruct(resultTypeId, constituents);
2357}
2358
John Kessenich140f3df2015-06-26 16:58:36 -06002359bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2360{
qining27e04a02016-04-14 16:40:20 -04002361 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2362 if (node->getType().getQualifier().isSpecConstant())
2363 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2364
John Kessenichfc51d282015-08-19 13:34:18 -06002365 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002366 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2367 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2368 // SPIR-V, for an out parameter
2369 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002370
John Kessenich8985fc92020-03-03 10:25:07 -07002371 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2372 invertedType :
2373 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002374
2375 // try texturing
2376 result = createImageTextureFunctionCall(node);
2377 if (result != spv::NoResult) {
2378 builder.clearAccessChain();
2379 builder.setAccessChainRValue(result);
2380
2381 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002382 }
2383#ifndef GLSLANG_WEB
2384 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002385 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002386 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002387 // "imageStore" is a special case, which has no result
2388 return false;
2389 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002390#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002391
John Kessenich140f3df2015-06-26 16:58:36 -06002392 glslang::TOperator binOp = glslang::EOpNull;
2393 bool reduceComparison = true;
2394 bool isMatrix = false;
2395 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002396 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002397
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002398 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2399
John Kessenich140f3df2015-06-26 16:58:36 -06002400 assert(node->getOp());
2401
John Kessenichf6640762016-08-01 19:44:00 -06002402 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002403
2404 switch (node->getOp()) {
2405 case glslang::EOpSequence:
2406 {
2407 if (preVisit)
2408 ++sequenceDepth;
2409 else
2410 --sequenceDepth;
2411
2412 if (sequenceDepth == 1) {
2413 // If this is the parent node of all the functions, we want to see them
2414 // early, so all call points have actual SPIR-V functions to reference.
2415 // In all cases, still let the traverser visit the children for us.
2416 makeFunctions(node->getAsAggregate()->getSequence());
2417
John Kessenich6fccb3c2016-09-19 16:01:41 -06002418 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002419 // anything else gets there, so visit out of order, doing them all now.
2420 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2421
John Kessenich6a60c2f2016-12-08 21:01:59 -07002422 // 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 -06002423 // so do them manually.
2424 visitFunctions(node->getAsAggregate()->getSequence());
2425
2426 return false;
2427 }
2428
2429 return true;
2430 }
2431 case glslang::EOpLinkerObjects:
2432 {
2433 if (visit == glslang::EvPreVisit)
2434 linkageOnly = true;
2435 else
2436 linkageOnly = false;
2437
2438 return true;
2439 }
2440 case glslang::EOpComma:
2441 {
2442 // processing from left to right naturally leaves the right-most
2443 // lying around in the access chain
2444 glslang::TIntermSequence& glslangOperands = node->getSequence();
2445 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2446 glslangOperands[i]->traverse(this);
2447
2448 return false;
2449 }
2450 case glslang::EOpFunction:
2451 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002452 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002453 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002454 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002455 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002456 } else {
2457 handleFunctionEntry(node);
2458 }
2459 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002460 if (inEntryPoint)
2461 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002462 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002463 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002464 }
2465
2466 return true;
2467 case glslang::EOpParameters:
2468 // Parameters will have been consumed by EOpFunction processing, but not
2469 // the body, so we still visited the function node's children, making this
2470 // child redundant.
2471 return false;
2472 case glslang::EOpFunctionCall:
2473 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002474 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002475 if (node->isUserDefined())
2476 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002477 if (result) {
2478 builder.clearAccessChain();
2479 builder.setAccessChainRValue(result);
2480 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002481 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002482
2483 return false;
2484 }
2485 case glslang::EOpConstructMat2x2:
2486 case glslang::EOpConstructMat2x3:
2487 case glslang::EOpConstructMat2x4:
2488 case glslang::EOpConstructMat3x2:
2489 case glslang::EOpConstructMat3x3:
2490 case glslang::EOpConstructMat3x4:
2491 case glslang::EOpConstructMat4x2:
2492 case glslang::EOpConstructMat4x3:
2493 case glslang::EOpConstructMat4x4:
2494 case glslang::EOpConstructDMat2x2:
2495 case glslang::EOpConstructDMat2x3:
2496 case glslang::EOpConstructDMat2x4:
2497 case glslang::EOpConstructDMat3x2:
2498 case glslang::EOpConstructDMat3x3:
2499 case glslang::EOpConstructDMat3x4:
2500 case glslang::EOpConstructDMat4x2:
2501 case glslang::EOpConstructDMat4x3:
2502 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002503 case glslang::EOpConstructIMat2x2:
2504 case glslang::EOpConstructIMat2x3:
2505 case glslang::EOpConstructIMat2x4:
2506 case glslang::EOpConstructIMat3x2:
2507 case glslang::EOpConstructIMat3x3:
2508 case glslang::EOpConstructIMat3x4:
2509 case glslang::EOpConstructIMat4x2:
2510 case glslang::EOpConstructIMat4x3:
2511 case glslang::EOpConstructIMat4x4:
2512 case glslang::EOpConstructUMat2x2:
2513 case glslang::EOpConstructUMat2x3:
2514 case glslang::EOpConstructUMat2x4:
2515 case glslang::EOpConstructUMat3x2:
2516 case glslang::EOpConstructUMat3x3:
2517 case glslang::EOpConstructUMat3x4:
2518 case glslang::EOpConstructUMat4x2:
2519 case glslang::EOpConstructUMat4x3:
2520 case glslang::EOpConstructUMat4x4:
2521 case glslang::EOpConstructBMat2x2:
2522 case glslang::EOpConstructBMat2x3:
2523 case glslang::EOpConstructBMat2x4:
2524 case glslang::EOpConstructBMat3x2:
2525 case glslang::EOpConstructBMat3x3:
2526 case glslang::EOpConstructBMat3x4:
2527 case glslang::EOpConstructBMat4x2:
2528 case glslang::EOpConstructBMat4x3:
2529 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002530 case glslang::EOpConstructF16Mat2x2:
2531 case glslang::EOpConstructF16Mat2x3:
2532 case glslang::EOpConstructF16Mat2x4:
2533 case glslang::EOpConstructF16Mat3x2:
2534 case glslang::EOpConstructF16Mat3x3:
2535 case glslang::EOpConstructF16Mat3x4:
2536 case glslang::EOpConstructF16Mat4x2:
2537 case glslang::EOpConstructF16Mat4x3:
2538 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002539 isMatrix = true;
2540 // fall through
2541 case glslang::EOpConstructFloat:
2542 case glslang::EOpConstructVec2:
2543 case glslang::EOpConstructVec3:
2544 case glslang::EOpConstructVec4:
2545 case glslang::EOpConstructDouble:
2546 case glslang::EOpConstructDVec2:
2547 case glslang::EOpConstructDVec3:
2548 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002549 case glslang::EOpConstructFloat16:
2550 case glslang::EOpConstructF16Vec2:
2551 case glslang::EOpConstructF16Vec3:
2552 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002553 case glslang::EOpConstructBool:
2554 case glslang::EOpConstructBVec2:
2555 case glslang::EOpConstructBVec3:
2556 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002557 case glslang::EOpConstructInt8:
2558 case glslang::EOpConstructI8Vec2:
2559 case glslang::EOpConstructI8Vec3:
2560 case glslang::EOpConstructI8Vec4:
2561 case glslang::EOpConstructUint8:
2562 case glslang::EOpConstructU8Vec2:
2563 case glslang::EOpConstructU8Vec3:
2564 case glslang::EOpConstructU8Vec4:
2565 case glslang::EOpConstructInt16:
2566 case glslang::EOpConstructI16Vec2:
2567 case glslang::EOpConstructI16Vec3:
2568 case glslang::EOpConstructI16Vec4:
2569 case glslang::EOpConstructUint16:
2570 case glslang::EOpConstructU16Vec2:
2571 case glslang::EOpConstructU16Vec3:
2572 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002573 case glslang::EOpConstructInt:
2574 case glslang::EOpConstructIVec2:
2575 case glslang::EOpConstructIVec3:
2576 case glslang::EOpConstructIVec4:
2577 case glslang::EOpConstructUint:
2578 case glslang::EOpConstructUVec2:
2579 case glslang::EOpConstructUVec3:
2580 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002581 case glslang::EOpConstructInt64:
2582 case glslang::EOpConstructI64Vec2:
2583 case glslang::EOpConstructI64Vec3:
2584 case glslang::EOpConstructI64Vec4:
2585 case glslang::EOpConstructUint64:
2586 case glslang::EOpConstructU64Vec2:
2587 case glslang::EOpConstructU64Vec3:
2588 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002589 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002590 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002591 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002592 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002593 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002594 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002595 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002596 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002597 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002598 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002599 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002600 else if (node->getOp() == glslang::EOpConstructStruct ||
2601 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2602 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002603 std::vector<spv::Id> constituents;
2604 for (int c = 0; c < (int)arguments.size(); ++c)
2605 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002606 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002607 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002608 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002609 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002610 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002611
2612 builder.clearAccessChain();
2613 builder.setAccessChainRValue(constructed);
2614
2615 return false;
2616 }
2617
2618 // These six are component-wise compares with component-wise results.
2619 // Forward on to createBinaryOperation(), requesting a vector result.
2620 case glslang::EOpLessThan:
2621 case glslang::EOpGreaterThan:
2622 case glslang::EOpLessThanEqual:
2623 case glslang::EOpGreaterThanEqual:
2624 case glslang::EOpVectorEqual:
2625 case glslang::EOpVectorNotEqual:
2626 {
2627 // Map the operation to a binary
2628 binOp = node->getOp();
2629 reduceComparison = false;
2630 switch (node->getOp()) {
2631 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2632 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2633 default: binOp = node->getOp(); break;
2634 }
2635
2636 break;
2637 }
2638 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002639 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002640 binOp = glslang::EOpMul;
2641 break;
2642 case glslang::EOpOuterProduct:
2643 // two vectors multiplied to make a matrix
2644 binOp = glslang::EOpOuterProduct;
2645 break;
2646 case glslang::EOpDot:
2647 {
qining25262b32016-05-06 17:25:16 -04002648 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002649 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002650 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002651 binOp = glslang::EOpMul;
2652 break;
2653 }
2654 case glslang::EOpMod:
2655 // when an aggregate, this is the floating-point mod built-in function,
2656 // which can be emitted by the one in createBinaryOperation()
2657 binOp = glslang::EOpMod;
2658 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002659
John Kessenich140f3df2015-06-26 16:58:36 -06002660 case glslang::EOpEmitVertex:
2661 case glslang::EOpEndPrimitive:
2662 case glslang::EOpBarrier:
2663 case glslang::EOpMemoryBarrier:
2664 case glslang::EOpMemoryBarrierAtomicCounter:
2665 case glslang::EOpMemoryBarrierBuffer:
2666 case glslang::EOpMemoryBarrierImage:
2667 case glslang::EOpMemoryBarrierShared:
2668 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002669 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002670 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002671 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002672 case glslang::EOpWorkgroupMemoryBarrier:
2673 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002674 case glslang::EOpSubgroupBarrier:
2675 case glslang::EOpSubgroupMemoryBarrier:
2676 case glslang::EOpSubgroupMemoryBarrierBuffer:
2677 case glslang::EOpSubgroupMemoryBarrierImage:
2678 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002679 noReturnValue = true;
2680 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2681 break;
2682
John Kessenich426394d2015-07-23 10:22:48 -06002683 case glslang::EOpAtomicAdd:
2684 case glslang::EOpAtomicMin:
2685 case glslang::EOpAtomicMax:
2686 case glslang::EOpAtomicAnd:
2687 case glslang::EOpAtomicOr:
2688 case glslang::EOpAtomicXor:
2689 case glslang::EOpAtomicExchange:
2690 case glslang::EOpAtomicCompSwap:
2691 atomic = true;
2692 break;
2693
John Kesseniche5eee8f2019-10-18 01:03:11 -06002694#ifndef GLSLANG_WEB
2695 case glslang::EOpAtomicStore:
2696 noReturnValue = true;
2697 // fallthrough
2698 case glslang::EOpAtomicLoad:
2699 atomic = true;
2700 break;
2701
John Kessenich0d0c6d32017-07-23 16:08:26 -06002702 case glslang::EOpAtomicCounterAdd:
2703 case glslang::EOpAtomicCounterSubtract:
2704 case glslang::EOpAtomicCounterMin:
2705 case glslang::EOpAtomicCounterMax:
2706 case glslang::EOpAtomicCounterAnd:
2707 case glslang::EOpAtomicCounterOr:
2708 case glslang::EOpAtomicCounterXor:
2709 case glslang::EOpAtomicCounterExchange:
2710 case glslang::EOpAtomicCounterCompSwap:
2711 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2712 builder.addCapability(spv::CapabilityAtomicStorageOps);
2713 atomic = true;
2714 break;
2715
Ian Romanickb3bd4022019-01-21 08:57:25 -08002716 case glslang::EOpAbsDifference:
2717 case glslang::EOpAddSaturate:
2718 case glslang::EOpSubSaturate:
2719 case glslang::EOpAverage:
2720 case glslang::EOpAverageRounded:
2721 case glslang::EOpMul32x16:
2722 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2723 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2724 binOp = node->getOp();
2725 break;
2726
Daniel Kochdb32b242020-03-17 20:42:47 -04002727 case glslang::EOpIgnoreIntersection:
2728 case glslang::EOpTerminateRay:
2729 case glslang::EOpTrace:
2730 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002731 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2732 noReturnValue = true;
2733 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002734 case glslang::EOpRayQueryInitialize:
2735 case glslang::EOpRayQueryTerminate:
2736 case glslang::EOpRayQueryGenerateIntersection:
2737 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002738 builder.addExtension("SPV_KHR_ray_query");
2739 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002740 noReturnValue = true;
2741 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002742 case glslang::EOpRayQueryProceed:
2743 case glslang::EOpRayQueryGetIntersectionType:
2744 case glslang::EOpRayQueryGetRayTMin:
2745 case glslang::EOpRayQueryGetRayFlags:
2746 case glslang::EOpRayQueryGetIntersectionT:
2747 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2748 case glslang::EOpRayQueryGetIntersectionInstanceId:
2749 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2750 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2751 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2752 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2753 case glslang::EOpRayQueryGetIntersectionFrontFace:
2754 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2755 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2756 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2757 case glslang::EOpRayQueryGetWorldRayDirection:
2758 case glslang::EOpRayQueryGetWorldRayOrigin:
2759 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2760 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2761 builder.addExtension("SPV_KHR_ray_query");
2762 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2763 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002764 case glslang::EOpCooperativeMatrixLoad:
2765 case glslang::EOpCooperativeMatrixStore:
2766 noReturnValue = true;
2767 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002768 case glslang::EOpBeginInvocationInterlock:
2769 case glslang::EOpEndInvocationInterlock:
2770 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2771 noReturnValue = true;
2772 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002773#endif
Chao Chen3c366992018-09-19 11:41:59 -07002774
Jeff Bolz04d73732019-05-31 13:06:01 -05002775 case glslang::EOpDebugPrintf:
2776 noReturnValue = true;
2777 break;
2778
John Kessenich140f3df2015-06-26 16:58:36 -06002779 default:
2780 break;
2781 }
2782
2783 //
2784 // See if it maps to a regular operation.
2785 //
John Kessenich140f3df2015-06-26 16:58:36 -06002786 if (binOp != glslang::EOpNull) {
2787 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2788 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2789 assert(left && right);
2790
2791 builder.clearAccessChain();
2792 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002793 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002794
2795 builder.clearAccessChain();
2796 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002797 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002798
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002799 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002800 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002801 TranslateNoContractionDecoration(node->getType().getQualifier()),
2802 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002803 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002804 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002805 left->getType().getBasicType(), reduceComparison);
2806
2807 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002808 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002809 builder.clearAccessChain();
2810 builder.setAccessChainRValue(result);
2811
2812 return false;
2813 }
2814
John Kessenich426394d2015-07-23 10:22:48 -06002815 //
2816 // Create the list of operands.
2817 //
John Kessenich140f3df2015-06-26 16:58:36 -06002818 glslang::TIntermSequence& glslangOperands = node->getSequence();
2819 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002820 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002821 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002822 // special case l-value operands; there are just a few
2823 bool lvalue = false;
2824 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002825 case glslang::EOpModf:
2826 if (arg == 1)
2827 lvalue = true;
2828 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002829
Torosdagli06c2eee2020-03-19 11:09:57 -04002830 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002831 case glslang::EOpRayQueryTerminate:
2832 case glslang::EOpRayQueryConfirmIntersection:
2833 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002834 case glslang::EOpRayQueryGenerateIntersection:
2835 case glslang::EOpRayQueryGetIntersectionType:
2836 case glslang::EOpRayQueryGetIntersectionT:
2837 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2838 case glslang::EOpRayQueryGetIntersectionInstanceId:
2839 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2840 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2841 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2842 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2843 case glslang::EOpRayQueryGetIntersectionFrontFace:
2844 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2845 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2846 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2847 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2848 if (arg == 0)
2849 lvalue = true;
2850 break;
2851
John Kesseniche5eee8f2019-10-18 01:03:11 -06002852 case glslang::EOpAtomicAdd:
2853 case glslang::EOpAtomicMin:
2854 case glslang::EOpAtomicMax:
2855 case glslang::EOpAtomicAnd:
2856 case glslang::EOpAtomicOr:
2857 case glslang::EOpAtomicXor:
2858 case glslang::EOpAtomicExchange:
2859 case glslang::EOpAtomicCompSwap:
2860 if (arg == 0)
2861 lvalue = true;
2862 break;
2863
John Kessenicha28f7a72019-08-06 07:00:58 -06002864#ifndef GLSLANG_WEB
2865 case glslang::EOpFrexp:
2866 if (arg == 1)
2867 lvalue = true;
2868 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002869 case glslang::EOpInterpolateAtSample:
2870 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002871 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002872 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002873 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002874
2875 // Does it need a swizzle inversion? If so, evaluation is inverted;
2876 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002877 // That is, we transform
2878 //
2879 // interpolate(v.zy) -> interpolate(v).zy
2880 //
John Kessenichecba76f2017-01-06 00:34:48 -07002881 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002882 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002883 invertedType = convertGlslangToSpvType(
2884 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002885 }
Rex Xu7a26c172015-12-08 17:12:09 +08002886 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002887 case glslang::EOpAtomicLoad:
2888 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002889 case glslang::EOpAtomicCounterAdd:
2890 case glslang::EOpAtomicCounterSubtract:
2891 case glslang::EOpAtomicCounterMin:
2892 case glslang::EOpAtomicCounterMax:
2893 case glslang::EOpAtomicCounterAnd:
2894 case glslang::EOpAtomicCounterOr:
2895 case glslang::EOpAtomicCounterXor:
2896 case glslang::EOpAtomicCounterExchange:
2897 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002898 if (arg == 0)
2899 lvalue = true;
2900 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002901 case glslang::EOpAddCarry:
2902 case glslang::EOpSubBorrow:
2903 if (arg == 2)
2904 lvalue = true;
2905 break;
2906 case glslang::EOpUMulExtended:
2907 case glslang::EOpIMulExtended:
2908 if (arg >= 2)
2909 lvalue = true;
2910 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002911 case glslang::EOpCooperativeMatrixLoad:
2912 if (arg == 0 || arg == 1)
2913 lvalue = true;
2914 break;
2915 case glslang::EOpCooperativeMatrixStore:
2916 if (arg == 1)
2917 lvalue = true;
2918 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002919#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002920 default:
2921 break;
2922 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002923 builder.clearAccessChain();
2924 if (invertedType != spv::NoType && arg == 0)
2925 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2926 else
2927 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002928
John Kessenichb9197c82019-08-11 07:41:45 -06002929#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002930 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2931 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2932
2933 if (arg == 1) {
2934 // fold "element" parameter into the access chain
2935 spv::Builder::AccessChain save = builder.getAccessChain();
2936 builder.clearAccessChain();
2937 glslangOperands[2]->traverse(this);
2938
2939 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2940
2941 builder.setAccessChain(save);
2942
2943 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002944 builder.accessChainPush(elementId,
2945 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2946 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002947
2948 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2949 unsigned int alignment = builder.getAccessChain().alignment;
2950
2951 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2952 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2953 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2954 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2955 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002956 if (builder.getStorageClass(builder.getAccessChain().base) ==
2957 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002958 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2959 }
2960
2961 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2962
2963 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2964 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2965 }
2966
John Kessenich8985fc92020-03-03 10:25:07 -07002967 if (memoryAccess &
2968 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2969 memoryAccessOperands.push_back(spv::IdImmediate(true,
2970 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002971 }
2972 } else if (arg == 2) {
2973 continue;
2974 }
2975 }
John Kessenichb9197c82019-08-11 07:41:45 -06002976#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002977
John Kessenichbbbd9a22020-03-03 07:21:37 -07002978 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002979 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002980 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2981 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2982 // reduce to a simple access chain. So, we need a temporary vector to
2983 // receive the result, and must later swizzle that into the original
2984 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06002985 complexLvalues.push_back(builder.getAccessChain());
John Kessenich435dd802020-06-30 01:27:08 -06002986 temporaryLvalues.push_back(builder.createVariable(
2987 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06002988 builder.accessChainGetInferredType(), "swizzleTemp"));
2989 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07002990 } else {
2991 operands.push_back(builder.accessChainGetLValue());
2992 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002993 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2994 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2995 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002996 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002997 glslang::TOperator glslangOp = node->getOp();
2998 if (arg == 1 &&
2999 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3000 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3001 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3002 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3003 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3004 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3005 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3006 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3007 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3008 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3009 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3010 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3011 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3012 )) {
3013 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3014 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3015 }
3016 else {
3017 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3018 }
3019
John Kesseniche485c7a2017-05-31 18:50:53 -06003020 }
John Kessenich140f3df2015-06-26 16:58:36 -06003021 }
John Kessenich426394d2015-07-23 10:22:48 -06003022
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003023 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003024#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003025 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3026 std::vector<spv::IdImmediate> idImmOps;
3027
3028 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3029 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3030 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3031 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3032 // get the pointee type
3033 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3034 assert(builder.isCooperativeMatrixType(typeId));
3035 // do the op
3036 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3037 // store the result to the pointer (out param 'm')
3038 builder.createStore(result, operands[0]);
3039 result = 0;
3040 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3041 std::vector<spv::IdImmediate> idImmOps;
3042
3043 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3044 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3045 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3046 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3047 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3048
3049 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3050 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003051 } else
3052#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003053 if (atomic) {
3054 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003055 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3056 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003057 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3058 if (!nonSemanticDebugPrintf) {
3059 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3060 }
3061 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3062 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003063 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003064 // Pass through to generic operations.
3065 switch (glslangOperands.size()) {
3066 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003067 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003068 break;
3069 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003070 {
3071 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003072 TranslateNoContractionDecoration(node->getType().getQualifier()),
3073 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003074 result = createUnaryOperation(
3075 node->getOp(), decorations,
3076 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003077 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003078 }
John Kessenich426394d2015-07-23 10:22:48 -06003079 break;
3080 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003081 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003082 break;
3083 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003084
John Kessenichbbbd9a22020-03-03 07:21:37 -07003085 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003086 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003087
3088 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3089 builder.setAccessChain(complexLvalues[i]);
John Kessenich435dd802020-06-30 01:27:08 -06003090 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003091 }
John Kessenich140f3df2015-06-26 16:58:36 -06003092 }
3093
3094 if (noReturnValue)
3095 return false;
3096
3097 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003098 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003099 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003100 } else {
3101 builder.clearAccessChain();
3102 builder.setAccessChainRValue(result);
3103 return false;
3104 }
3105}
3106
John Kessenich433e9ff2017-01-26 20:31:11 -07003107// This path handles both if-then-else and ?:
3108// The if-then-else has a node type of void, while
3109// ?: has either a void or a non-void node type
3110//
3111// Leaving the result, when not void:
3112// GLSL only has r-values as the result of a :?, but
3113// if we have an l-value, that can be more efficient if it will
3114// become the base of a complex r-value expression, because the
3115// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003116bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3117{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003118 // see if OpSelect can handle it
3119 const auto isOpSelectable = [&]() {
3120 if (node->getBasicType() == glslang::EbtVoid)
3121 return false;
3122 // OpSelect can do all other types starting with SPV 1.4
3123 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3124 // pre-1.4, only scalars and vectors can be handled
3125 if ((!node->getType().isScalar() && !node->getType().isVector()))
3126 return false;
3127 }
3128 return true;
3129 };
3130
John Kessenich4bee5312018-02-20 21:29:05 -07003131 // See if it simple and safe, or required, to execute both sides.
3132 // Crucially, side effects must be either semantically required or avoided,
3133 // and there are performance trade-offs.
3134 // Return true if required or a good idea (and safe) to execute both sides,
3135 // false otherwise.
3136 const auto bothSidesPolicy = [&]() -> bool {
3137 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003138 if (node->getTrueBlock() == nullptr ||
3139 node->getFalseBlock() == nullptr)
3140 return false;
3141
John Kessenich4bee5312018-02-20 21:29:05 -07003142 // required? (unless we write additional code to look for side effects
3143 // and make performance trade-offs if none are present)
3144 if (!node->getShortCircuit())
3145 return true;
3146
3147 // if not required to execute both, decide based on performance/practicality...
3148
John Kessenich0c1e71a2019-01-10 18:23:06 +07003149 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003150 return false;
3151
John Kessenich433e9ff2017-01-26 20:31:11 -07003152 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3153 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3154
3155 // return true if a single operand to ? : is okay for OpSelect
3156 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003157 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003158 };
3159
3160 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3161 operandOkay(node->getFalseBlock()->getAsTyped());
3162 };
3163
John Kessenich4bee5312018-02-20 21:29:05 -07003164 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3165 // emit the condition before doing anything with selection
3166 node->getCondition()->traverse(this);
3167 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3168
3169 // Find a way of executing both sides and selecting the right result.
3170 const auto executeBothSides = [&]() -> void {
3171 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003172 node->getTrueBlock()->traverse(this);
3173 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3174 node->getFalseBlock()->traverse(this);
3175 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3176
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003177 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003178
John Kessenich4bee5312018-02-20 21:29:05 -07003179 // done if void
3180 if (node->getBasicType() == glslang::EbtVoid)
3181 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003182
John Kessenich4bee5312018-02-20 21:29:05 -07003183 // emit code to select between trueValue and falseValue
3184
3185 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003186 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003187 // Emit OpSelect for this selection.
3188
3189 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003190 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3191 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003192 condition = builder.smearScalar(spv::NoPrecision, condition,
3193 builder.makeVectorType(builder.makeBoolType(),
3194 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003195 }
John Kessenich4bee5312018-02-20 21:29:05 -07003196
3197 // OpSelect
3198 result = builder.createTriOp(spv::OpSelect,
3199 convertGlslangToSpvType(node->getType()), condition,
3200 trueValue, falseValue);
3201
3202 builder.clearAccessChain();
3203 builder.setAccessChainRValue(result);
3204 } else {
3205 // We need control flow to select the result.
3206 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003207 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3208 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003209
3210 // Selection control:
3211 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3212
3213 // make an "if" based on the value created by the condition
3214 spv::Builder::If ifBuilder(condition, control, builder);
3215
3216 // emit the "then" statement
3217 builder.createStore(trueValue, result);
3218 ifBuilder.makeBeginElse();
3219 // emit the "else" statement
3220 builder.createStore(falseValue, result);
3221
3222 // finish off the control flow
3223 ifBuilder.makeEndIf();
3224
3225 builder.clearAccessChain();
3226 builder.setAccessChainLValue(result);
3227 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003228 };
3229
John Kessenich4bee5312018-02-20 21:29:05 -07003230 // Execute the one side needed, as per the condition
3231 const auto executeOneSide = [&]() {
3232 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003233 if (node->getBasicType() != glslang::EbtVoid) {
3234 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3235 convertGlslangToSpvType(node->getType()));
3236 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003237
John Kessenich4bee5312018-02-20 21:29:05 -07003238 // Selection control:
3239 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3240
3241 // make an "if" based on the value created by the condition
3242 spv::Builder::If ifBuilder(condition, control, builder);
3243
3244 // emit the "then" statement
3245 if (node->getTrueBlock() != nullptr) {
3246 node->getTrueBlock()->traverse(this);
3247 if (result != spv::NoResult)
3248 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3249 }
3250
3251 if (node->getFalseBlock() != nullptr) {
3252 ifBuilder.makeBeginElse();
3253 // emit the "else" statement
3254 node->getFalseBlock()->traverse(this);
3255 if (result != spv::NoResult)
3256 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3257 }
3258
3259 // finish off the control flow
3260 ifBuilder.makeEndIf();
3261
3262 if (result != spv::NoResult) {
3263 builder.clearAccessChain();
3264 builder.setAccessChainLValue(result);
3265 }
3266 };
3267
3268 // Try for OpSelect (or a requirement to execute both sides)
3269 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003270 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3271 if (node->getType().getQualifier().isSpecConstant())
3272 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003273 executeBothSides();
3274 } else
3275 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003276
3277 return false;
3278}
3279
3280bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3281{
3282 // emit and get the condition before doing anything with switch
3283 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003284 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003285
Rex Xu57e65922017-07-04 23:23:40 +08003286 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003287 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003288
John Kessenich140f3df2015-06-26 16:58:36 -06003289 // browse the children to sort out code segments
3290 int defaultSegment = -1;
3291 std::vector<TIntermNode*> codeSegments;
3292 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3293 std::vector<int> caseValues;
3294 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3295 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3296 TIntermNode* child = *c;
3297 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003298 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003299 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003300 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003301 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3302 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003303 } else
3304 codeSegments.push_back(child);
3305 }
3306
qining25262b32016-05-06 17:25:16 -04003307 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003308 // statements between the last case and the end of the switch statement
3309 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3310 (int)codeSegments.size() == defaultSegment)
3311 codeSegments.push_back(nullptr);
3312
3313 // make the switch statement
3314 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003315 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3316 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003317
3318 // emit all the code in the segments
3319 breakForLoop.push(false);
3320 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3321 builder.nextSwitchSegment(segmentBlocks, s);
3322 if (codeSegments[s])
3323 codeSegments[s]->traverse(this);
3324 else
3325 builder.addSwitchBreak();
3326 }
3327 breakForLoop.pop();
3328
3329 builder.endSwitch(segmentBlocks);
3330
3331 return false;
3332}
3333
3334void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3335{
3336 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003337 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003338
3339 builder.clearAccessChain();
3340 builder.setAccessChainRValue(constant);
3341}
3342
3343bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3344{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003345 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003346 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003347
3348 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003349 std::vector<unsigned int> operands;
3350 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003351
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003352 // Spec requires back edges to target header blocks, and every header block
3353 // must dominate its merge block. Make a header block first to ensure these
3354 // conditions are met. By definition, it will contain OpLoopMerge, followed
3355 // by a block-ending branch. But we don't want to put any other body/test
3356 // instructions in it, since the body/test may have arbitrary instructions,
3357 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003358 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003359 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003360 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003361 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003362 spv::Block& test = builder.makeNewBlock();
3363 builder.createBranch(&test);
3364
3365 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003366 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003367 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003368 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3369
3370 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003371 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003372 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003373 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003374 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003375 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003376
3377 builder.setBuildPoint(&blocks.continue_target);
3378 if (node->getTerminal())
3379 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003380 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003381 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003382 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003383 builder.createBranch(&blocks.body);
3384
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003385 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003386 builder.setBuildPoint(&blocks.body);
3387 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003388 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003389 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003390 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003391
3392 builder.setBuildPoint(&blocks.continue_target);
3393 if (node->getTerminal())
3394 node->getTerminal()->traverse(this);
3395 if (node->getTest()) {
3396 node->getTest()->traverse(this);
3397 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003398 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003399 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003400 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003401 // TODO: unless there was a break/return/discard instruction
3402 // somewhere in the body, this is an infinite loop, so we should
3403 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003404 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003405 }
John Kessenich140f3df2015-06-26 16:58:36 -06003406 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003407 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003408 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003409 return false;
3410}
3411
3412bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3413{
3414 if (node->getExpression())
3415 node->getExpression()->traverse(this);
3416
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003417 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003418
John Kessenich140f3df2015-06-26 16:58:36 -06003419 switch (node->getFlowOp()) {
3420 case glslang::EOpKill:
3421 builder.makeDiscard();
3422 break;
3423 case glslang::EOpBreak:
3424 if (breakForLoop.top())
3425 builder.createLoopExit();
3426 else
3427 builder.addSwitchBreak();
3428 break;
3429 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003430 builder.createLoopContinue();
3431 break;
3432 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003433 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003434 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3435 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003436 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3437 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003438 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003439 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3440 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003441 builder.setAccessChainLValue(copyId);
3442 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003443 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003444 }
3445 builder.makeReturn(false, returnId);
3446 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003447 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003448
3449 builder.clearAccessChain();
3450 break;
3451
John Kessenichb9197c82019-08-11 07:41:45 -06003452#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003453 case glslang::EOpDemote:
3454 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3455 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3456 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3457 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003458#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003459
John Kessenich140f3df2015-06-26 16:58:36 -06003460 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003461 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003462 break;
3463 }
3464
3465 return false;
3466}
3467
John Kessenich9c14f772019-06-17 08:38:35 -06003468spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003469{
qining25262b32016-05-06 17:25:16 -04003470 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003471 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003472 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003473 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003474 spv::Id result = createSpvConstant(*node);
3475 if (result != spv::NoResult)
3476 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003477 }
3478
3479 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003480 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003481 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3482 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003483
John Kessenichb9197c82019-08-11 07:41:45 -06003484 const bool contains16BitType = node->getType().contains16BitFloat() ||
3485 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003486 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003487 switch (storageClass) {
3488 case spv::StorageClassInput:
3489 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003490 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003491 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003492 break;
John Kessenich18310872018-05-14 22:08:53 -06003493 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003494 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003495 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3496 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003497 else
3498 builder.addCapability(spv::CapabilityStorageUniform16);
3499 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003500#ifndef GLSLANG_WEB
3501 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003502 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003503 builder.addCapability(spv::CapabilityStoragePushConstant16);
3504 break;
John Kessenich18310872018-05-14 22:08:53 -06003505 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003506 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003507 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003508 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3509 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003510#endif
John Kessenich18310872018-05-14 22:08:53 -06003511 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003512 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003513 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003514 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003515 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003516 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003517 }
3518 }
Rex Xuf89ad982017-04-07 23:22:33 +08003519
John Kessenichb9197c82019-08-11 07:41:45 -06003520 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003521 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003522 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003523 builder.addCapability(spv::CapabilityStoragePushConstant8);
3524 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003525 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003526 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003527 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003528 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003529 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003530 } else {
3531 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003532 }
3533 }
3534
John Kessenich140f3df2015-06-26 16:58:36 -06003535 const char* name = node->getName().c_str();
3536 if (glslang::IsAnonymous(name))
3537 name = "";
3538
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003539 spv::Id initializer = spv::NoResult;
3540
3541 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3542 !node->getConstArray().empty()) {
3543 int nextConst = 0;
3544 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3545 node->getConstArray(),
3546 nextConst,
3547 false /* specConst */);
3548 }
3549
John Kessenich435dd802020-06-30 01:27:08 -06003550 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003551}
3552
3553// Return type Id of the sampled type.
3554spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3555{
3556 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003557 case glslang::EbtInt: return builder.makeIntType(32);
3558 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003559 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003560#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003561 case glslang::EbtFloat16:
3562 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3563 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3564 return builder.makeFloatType(16);
3565#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003566 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003567 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003568 return builder.makeFloatType(32);
3569 }
3570}
3571
John Kessenich8c8505c2016-07-26 12:50:38 -06003572// If node is a swizzle operation, return the type that should be used if
3573// the swizzle base is first consumed by another operation, before the swizzle
3574// is applied.
3575spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3576{
John Kessenichecba76f2017-01-06 00:34:48 -07003577 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003578 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3579 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3580 else
3581 return spv::NoType;
3582}
3583
3584// When inverting a swizzle with a parent op, this function
3585// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003586spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3587 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003588{
3589 std::vector<unsigned> swizzle;
3590 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3591 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3592}
3593
John Kessenich8c8505c2016-07-26 12:50:38 -06003594// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3595void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3596{
3597 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3598 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3599 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3600}
3601
John Kessenich3ac051e2015-12-20 11:29:16 -07003602// Convert from a glslang type to an SPV type, by calling into a
3603// recursive version of this function. This establishes the inherited
3604// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003605spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003606{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003607 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003608}
3609
3610// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003611// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003612// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003613spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003614 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3615 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003616{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003617 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003618
3619 switch (type.getBasicType()) {
3620 case glslang::EbtVoid:
3621 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003622 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003623 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003624 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003625 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3626 // a 32-bit int where non-0 means true.
3627 if (explicitLayout != glslang::ElpNone)
3628 spvType = builder.makeUintType(32);
3629 else
3630 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003631 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003632 case glslang::EbtInt:
3633 spvType = builder.makeIntType(32);
3634 break;
3635 case glslang::EbtUint:
3636 spvType = builder.makeUintType(32);
3637 break;
3638 case glslang::EbtFloat:
3639 spvType = builder.makeFloatType(32);
3640 break;
3641#ifndef GLSLANG_WEB
3642 case glslang::EbtDouble:
3643 spvType = builder.makeFloatType(64);
3644 break;
3645 case glslang::EbtFloat16:
3646 spvType = builder.makeFloatType(16);
3647 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003648 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003649 spvType = builder.makeIntType(8);
3650 break;
3651 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003652 spvType = builder.makeUintType(8);
3653 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003654 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003655 spvType = builder.makeIntType(16);
3656 break;
3657 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003658 spvType = builder.makeUintType(16);
3659 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003660 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003661 spvType = builder.makeIntType(64);
3662 break;
3663 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003664 spvType = builder.makeUintType(64);
3665 break;
John Kessenich426394d2015-07-23 10:22:48 -06003666 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003667 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003668 spvType = builder.makeUintType(32);
3669 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003670 case glslang::EbtAccStruct:
3671 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003672 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003673 case glslang::EbtRayQuery:
3674 spvType = builder.makeRayQueryType();
3675 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003676 case glslang::EbtReference:
3677 {
3678 // Make the forward pointer, then recurse to convert the structure type, then
3679 // patch up the forward pointer with a real pointer type.
3680 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3681 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3682 forwardPointers[type.getReferentType()] = forwardId;
3683 }
3684 spvType = forwardPointers[type.getReferentType()];
3685 if (!forwardReferenceOnly) {
3686 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3687 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3688 forwardPointers[type.getReferentType()],
3689 referentType);
3690 }
3691 }
3692 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003693#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003694 case glslang::EbtSampler:
3695 {
3696 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003697 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003698 spvType = builder.makeSamplerType();
3699 } else {
3700 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003701 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3702 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3703 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3704 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003705 // already has both image and sampler, make the combined type
3706 spvType = builder.makeSampledImageType(spvType);
3707 }
John Kessenich55e7d112015-11-15 21:33:39 -07003708 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003709 }
John Kessenich140f3df2015-06-26 16:58:36 -06003710 break;
3711 case glslang::EbtStruct:
3712 case glslang::EbtBlock:
3713 {
3714 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003715 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003716
3717 // Try to share structs for different layouts, but not yet for other
3718 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003719 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003720 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003721 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723
3724 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003725 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003726 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003727 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003728 }
3729 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003730 case glslang::EbtString:
3731 // no type used for OpString
3732 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003733 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003734 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 }
3737
3738 if (type.isMatrix())
3739 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3740 else {
3741 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3742 if (type.getVectorSize() > 1)
3743 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3744 }
3745
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003746 if (type.isCoopMat()) {
3747 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3748 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3749 if (type.getBasicType() == glslang::EbtFloat16)
3750 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003751 if (type.getBasicType() == glslang::EbtUint8 ||
3752 type.getBasicType() == glslang::EbtInt8) {
3753 builder.addCapability(spv::CapabilityInt8);
3754 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003755
3756 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3757 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3758 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3759
3760 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3761 }
3762
John Kessenich140f3df2015-06-26 16:58:36 -06003763 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003764 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3765
John Kessenichc9a80832015-09-12 12:17:44 -06003766 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003767 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003768 // We need to decorate array strides for types needing explicit layout, except blocks.
3769 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003770 // Use a dummy glslang type for querying internal strides of
3771 // arrays of arrays, but using just a one-dimensional array.
3772 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003773 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3774 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003775
3776 // Will compute the higher-order strides here, rather than making a whole
3777 // pile of types and doing repetitive recursion on their contents.
3778 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3779 }
John Kessenichf8842e52016-01-04 19:22:56 -07003780
3781 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003782 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003783 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003784 if (stride > 0)
3785 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003786 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003787 }
3788 } else {
3789 // single-dimensional array, and don't yet have stride
3790
John Kessenichf8842e52016-01-04 19:22:56 -07003791 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003792 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3793 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003794 }
John Kessenich31ed4832015-09-09 17:51:38 -06003795
John Kessenichead86222018-03-28 18:01:20 -06003796 // Do the outer dimension, which might not be known for a runtime-sized array.
3797 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3798 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003799 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003800 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003801#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003802 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003803 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003804 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3805 }
John Kessenichb9197c82019-08-11 07:41:45 -06003806#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003807 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003808 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003809 if (stride > 0)
3810 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003811 }
3812
3813 return spvType;
3814}
3815
John Kessenich0e737842017-03-24 18:38:16 -06003816// TODO: this functionality should exist at a higher level, in creating the AST
3817//
3818// Identify interface members that don't have their required extension turned on.
3819//
3820bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3821{
John Kessenicha28f7a72019-08-06 07:00:58 -06003822#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003823 auto& extensions = glslangIntermediate->getRequestedExtensions();
3824
Rex Xubcf291a2017-03-29 23:01:36 +08003825 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3826 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3827 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003828 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3829 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3830 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003831
3832 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3833 if (member.getFieldName() == "gl_ViewportMask" &&
3834 extensions.find("GL_NV_viewport_array2") == extensions.end())
3835 return true;
3836 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3837 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3838 return true;
3839 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3840 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3841 return true;
3842 }
3843#endif
John Kessenich0e737842017-03-24 18:38:16 -06003844
3845 return false;
3846};
3847
John Kessenich6090df02016-06-30 21:18:02 -06003848// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3849// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3850// Mutually recursive with convertGlslangToSpvType().
3851spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3852 const glslang::TTypeList* glslangMembers,
3853 glslang::TLayoutPacking explicitLayout,
3854 const glslang::TQualifier& qualifier)
3855{
3856 // Create a vector of struct types for SPIR-V to consume
3857 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003858 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3859 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003860 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003861 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3862 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3863 if (glslangMember.hiddenMember()) {
3864 ++memberDelta;
3865 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003866 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003867 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003868 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003869 if (filterMember(glslangMember)) {
3870 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003871 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003872 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003873 }
Roy05a5b532020-01-03 16:21:34 +08003874 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003875 }
John Kessenich6090df02016-06-30 21:18:02 -06003876 // modify just this child's view of the qualifier
3877 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3878 InheritQualifiers(memberQualifier, qualifier);
3879
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003880 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003881 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003882 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003883
3884 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003885 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3886 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003887
3888 // Make forward pointers for any pointer members, and create a list of members to
3889 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003890 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003891 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3892 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3893 }
3894 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003895 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3896 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003897 } else {
3898 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003899 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3900 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003901 }
John Kessenich6090df02016-06-30 21:18:02 -06003902 }
3903 }
3904
3905 // Make the SPIR-V type
3906 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003907 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003908 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3909
3910 // Decorate it
3911 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3912
John Kessenichd72f4882019-01-16 14:55:37 +07003913 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003914 auto it = deferredForwardPointers[i];
3915 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3916 }
3917
John Kessenich6090df02016-06-30 21:18:02 -06003918 return spvType;
3919}
3920
3921void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3922 const glslang::TTypeList* glslangMembers,
3923 glslang::TLayoutPacking explicitLayout,
3924 const glslang::TQualifier& qualifier,
3925 spv::Id spvType)
3926{
3927 // Name and decorate the non-hidden members
3928 int offset = -1;
3929 int locationOffset = 0; // for use within the members of this struct
3930 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3931 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3932 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003933 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003934 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003935 if (filterMember(glslangMember))
3936 continue;
3937 }
John Kessenich6090df02016-06-30 21:18:02 -06003938
3939 // modify just this child's view of the qualifier
3940 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3941 InheritQualifiers(memberQualifier, qualifier);
3942
3943 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003944 if (member < 0)
3945 continue;
3946
3947 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3948 builder.addMemberDecoration(spvType, member,
3949 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3950 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3951 // Add interpolation and auxiliary storage decorations only to
3952 // top-level members of Input and Output storage classes
3953 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3954 type.getQualifier().storage == glslang::EvqVaryingOut) {
3955 if (type.getBasicType() == glslang::EbtBlock ||
3956 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3957 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3958 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003959#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003960 addMeshNVDecoration(spvType, member, memberQualifier);
3961#endif
John Kessenich6090df02016-06-30 21:18:02 -06003962 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003963 }
3964 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003965
John Kessenichb9197c82019-08-11 07:41:45 -06003966#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003967 if (type.getBasicType() == glslang::EbtBlock &&
3968 qualifier.storage == glslang::EvqBuffer) {
3969 // Add memory decorations only to top-level members of shader storage block
3970 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003971 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003972 for (unsigned int i = 0; i < memory.size(); ++i)
3973 builder.addMemberDecoration(spvType, member, memory[i]);
3974 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003975
John Kessenichb9197c82019-08-11 07:41:45 -06003976#endif
John Kessenich6090df02016-06-30 21:18:02 -06003977
John Kessenich5d610ee2018-03-07 18:05:55 -07003978 // Location assignment was already completed correctly by the front end,
3979 // just track whether a member needs to be decorated.
3980 // Ignore member locations if the container is an array, as that's
3981 // ill-specified and decisions have been made to not allow this.
3982 if (! type.isArray() && memberQualifier.hasLocation())
3983 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003984
John Kessenich5d610ee2018-03-07 18:05:55 -07003985 if (qualifier.hasLocation()) // track for upcoming inheritance
3986 locationOffset += glslangIntermediate->computeTypeLocationSize(
3987 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003988
John Kessenich5d610ee2018-03-07 18:05:55 -07003989 // component, XFB, others
3990 if (glslangMember.getQualifier().hasComponent())
3991 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3992 glslangMember.getQualifier().layoutComponent);
3993 if (glslangMember.getQualifier().hasXfbOffset())
3994 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3995 glslangMember.getQualifier().layoutXfbOffset);
3996 else if (explicitLayout != glslang::ElpNone) {
3997 // figure out what to do with offset, which is accumulating
3998 int nextOffset;
3999 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4000 if (offset >= 0)
4001 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4002 offset = nextOffset;
4003 }
John Kessenich6090df02016-06-30 21:18:02 -06004004
John Kessenich5d610ee2018-03-07 18:05:55 -07004005 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4006 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4007 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004008
John Kessenich5d610ee2018-03-07 18:05:55 -07004009 // built-in variable decorations
4010 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4011 if (builtIn != spv::BuiltInMax)
4012 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004013
John Kessenichb9197c82019-08-11 07:41:45 -06004014#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004015 // nonuniform
4016 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4017
John Kessenichead86222018-03-28 18:01:20 -06004018 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4019 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4020 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4021 memberQualifier.semanticName);
4022 }
4023
John Kessenich5d610ee2018-03-07 18:05:55 -07004024 if (builtIn == spv::BuiltInLayer) {
4025 // SPV_NV_viewport_array2 extension
4026 if (glslangMember.getQualifier().layoutViewportRelative){
4027 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4028 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4029 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004030 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004031 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4032 builder.addMemberDecoration(spvType, member,
4033 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4034 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4035 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4036 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004037 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004038 }
4039 if (glslangMember.getQualifier().layoutPassthrough) {
4040 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4041 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4042 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4043 }
chaoc771d89f2017-01-13 01:10:53 -08004044#endif
John Kessenich6090df02016-06-30 21:18:02 -06004045 }
4046
4047 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004048 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4049 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004050}
4051
John Kessenich6c292d32016-02-15 20:58:50 -07004052// Turn the expression forming the array size into an id.
4053// This is not quite trivial, because of specialization constants.
4054// Sometimes, a raw constant is turned into an Id, and sometimes
4055// a specialization constant expression is.
4056spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4057{
4058 // First, see if this is sized with a node, meaning a specialization constant:
4059 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4060 if (specNode != nullptr) {
4061 builder.clearAccessChain();
4062 specNode->traverse(this);
4063 return accessChainLoad(specNode->getAsTyped()->getType());
4064 }
qining25262b32016-05-06 17:25:16 -04004065
John Kessenich6c292d32016-02-15 20:58:50 -07004066 // Otherwise, need a compile-time (front end) size, get it:
4067 int size = arraySizes.getDimSize(dim);
4068 assert(size > 0);
4069 return builder.makeUintConstant(size);
4070}
4071
John Kessenich103bef92016-02-08 21:38:15 -07004072// Wrap the builder's accessChainLoad to:
4073// - localize handling of RelaxedPrecision
4074// - use the SPIR-V inferred type instead of another conversion of the glslang type
4075// (avoids unnecessary work and possible type punning for structures)
4076// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004077spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4078{
John Kessenich103bef92016-02-08 21:38:15 -07004079 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004080
4081 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4082 coherentFlags |= TranslateCoherent(type);
4083
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004084 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004085 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004086
John Kessenich5611c6d2018-04-05 11:25:02 -06004087 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004088 TranslateNonUniformDecoration(type.getQualifier()),
4089 nominalTypeId,
4090 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4091 TranslateMemoryScope(coherentFlags),
4092 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004093
4094 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004095 if (type.getBasicType() == glslang::EbtBool) {
4096 if (builder.isScalarType(nominalTypeId)) {
4097 // Conversion for bool
4098 spv::Id boolType = builder.makeBoolType();
4099 if (nominalTypeId != boolType)
4100 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4101 } else if (builder.isVectorType(nominalTypeId)) {
4102 // Conversion for bvec
4103 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4104 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4105 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004106 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4107 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004108 }
4109 }
John Kessenich103bef92016-02-08 21:38:15 -07004110
4111 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004112}
4113
Rex Xu27253232016-02-23 17:51:09 +08004114// Wrap the builder's accessChainStore to:
4115// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004116//
4117// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004118void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4119{
4120 // Need to convert to abstract types when necessary
4121 if (type.getBasicType() == glslang::EbtBool) {
4122 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4123
4124 if (builder.isScalarType(nominalTypeId)) {
4125 // Conversion for bool
4126 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004127 if (nominalTypeId != boolType) {
4128 // keep these outside arguments, for determinant order-of-evaluation
4129 spv::Id one = builder.makeUintConstant(1);
4130 spv::Id zero = builder.makeUintConstant(0);
4131 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4132 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004133 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004134 } else if (builder.isVectorType(nominalTypeId)) {
4135 // Conversion for bvec
4136 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4137 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004138 if (nominalTypeId != bvecType) {
4139 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004140 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4141 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4142 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004143 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004144 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4145 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004146 }
4147 }
4148
Jeff Bolz36831c92018-09-05 10:11:41 -05004149 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4150 coherentFlags |= TranslateCoherent(type);
4151
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004152 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004153 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004154
Jeff Bolz36831c92018-09-05 10:11:41 -05004155 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004156 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4157 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004158 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004159}
4160
John Kessenich4bf71552016-09-02 11:20:21 -06004161// For storing when types match at the glslang level, but not might match at the
4162// SPIR-V level.
4163//
4164// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004165// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004166// as in a member-decorated way.
4167//
4168// NOTE: This function can handle any store request; if it's not special it
4169// simplifies to a simple OpStore.
4170//
4171// Implicitly uses the existing builder.accessChain as the storage target.
4172void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4173{
John Kessenichb3e24e42016-09-11 12:33:43 -06004174 // we only do the complex path here if it's an aggregate
4175 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004176 accessChainStore(type, rValue);
4177 return;
4178 }
4179
John Kessenichb3e24e42016-09-11 12:33:43 -06004180 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004181 spv::Id rType = builder.getTypeId(rValue);
4182 spv::Id lValue = builder.accessChainGetLValue();
4183 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4184 if (lType == rType) {
4185 accessChainStore(type, rValue);
4186 return;
4187 }
4188
John Kessenichb3e24e42016-09-11 12:33:43 -06004189 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004190 // where the two types were the same type in GLSL. This requires member
4191 // by member copy, recursively.
4192
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004193 // SPIR-V 1.4 added an instruction to do help do this.
4194 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4195 // However, bool in uniform space is changed to int, so
4196 // OpCopyLogical does not work for that.
4197 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4198 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4199 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4200 if (lBool == rBool) {
4201 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4202 accessChainStore(type, logicalCopy);
4203 return;
4204 }
4205 }
4206
John Kessenichb3e24e42016-09-11 12:33:43 -06004207 // If an array, copy element by element.
4208 if (type.isArray()) {
4209 glslang::TType glslangElementType(type, 0);
4210 spv::Id elementRType = builder.getContainedTypeId(rType);
4211 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4212 // get the source member
4213 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004214
John Kessenichb3e24e42016-09-11 12:33:43 -06004215 // set up the target storage
4216 builder.clearAccessChain();
4217 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004218 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4219 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004220
John Kessenichb3e24e42016-09-11 12:33:43 -06004221 // store the member
4222 multiTypeStore(glslangElementType, elementRValue);
4223 }
4224 } else {
4225 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004226
John Kessenichb3e24e42016-09-11 12:33:43 -06004227 // loop over structure members
4228 const glslang::TTypeList& members = *type.getStruct();
4229 for (int m = 0; m < (int)members.size(); ++m) {
4230 const glslang::TType& glslangMemberType = *members[m].type;
4231
4232 // get the source member
4233 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4234 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4235
4236 // set up the target storage
4237 builder.clearAccessChain();
4238 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004239 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4240 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004241
4242 // store the member
4243 multiTypeStore(glslangMemberType, memberRValue);
4244 }
John Kessenich4bf71552016-09-02 11:20:21 -06004245 }
4246}
4247
John Kessenichf85e8062015-12-19 13:57:10 -07004248// Decide whether or not this type should be
4249// decorated with offsets and strides, and if so
4250// whether std140 or std430 rules should be applied.
4251glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004252{
John Kessenichf85e8062015-12-19 13:57:10 -07004253 // has to be a block
4254 if (type.getBasicType() != glslang::EbtBlock)
4255 return glslang::ElpNone;
4256
Chao Chen3c366992018-09-19 11:41:59 -07004257 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004258 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004259 type.getQualifier().storage != glslang::EvqBuffer &&
4260 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004261 return glslang::ElpNone;
4262
4263 // return the layout to use
4264 switch (type.getQualifier().layoutPacking) {
4265 case glslang::ElpStd140:
4266 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004267 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004268 return type.getQualifier().layoutPacking;
4269 default:
4270 return glslang::ElpNone;
4271 }
John Kessenich31ed4832015-09-09 17:51:38 -06004272}
4273
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004274// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004275int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4276 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004277{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004278 int size;
John Kessenich49987892015-12-29 17:11:44 -07004279 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004280 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4281 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004282
4283 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004284}
4285
John Kessenich49987892015-12-29 17:11:44 -07004286// 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 -07004287// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004288int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4289 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004290{
John Kessenich49987892015-12-29 17:11:44 -07004291 glslang::TType elementType;
4292 elementType.shallowCopy(matrixType);
4293 elementType.clearArraySizes();
4294
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004295 int size;
John Kessenich49987892015-12-29 17:11:44 -07004296 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004297 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4298 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004299
4300 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004301}
4302
John Kessenich5e4b1242015-08-06 22:53:06 -06004303// Given a member type of a struct, realign the current offset for it, and compute
4304// the next (not yet aligned) offset for the next member, which will get aligned
4305// on the next call.
4306// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4307// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4308// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004309void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4310 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004311{
4312 // this will get a positive value when deemed necessary
4313 nextOffset = -1;
4314
John Kessenich5e4b1242015-08-06 22:53:06 -06004315 // override anything in currentOffset with user-set offset
4316 if (memberType.getQualifier().hasOffset())
4317 currentOffset = memberType.getQualifier().layoutOffset;
4318
4319 // It could be that current linker usage in glslang updated all the layoutOffset,
4320 // in which case the following code does not matter. But, that's not quite right
4321 // once cross-compilation unit GLSL validation is done, as the original user
4322 // settings are needed in layoutOffset, and then the following will come into play.
4323
John Kessenichf85e8062015-12-19 13:57:10 -07004324 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004325 if (! memberType.getQualifier().hasOffset())
4326 currentOffset = -1;
4327
4328 return;
4329 }
4330
John Kessenichf85e8062015-12-19 13:57:10 -07004331 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004332 if (currentOffset < 0)
4333 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004334
John Kessenich5e4b1242015-08-06 22:53:06 -06004335 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4336 // but possibly not yet correctly aligned.
4337
4338 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004339 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004340 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4341 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004342
4343 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004344 // TODO: make this consistent in early phases of code:
4345 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4346 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4347 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004348 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004349 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004350 int dummySize;
4351 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4352 if (componentAlignment <= 4)
4353 memberAlignment = componentAlignment;
4354 }
4355
4356 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004357 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004358
4359 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004360 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4361 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004362 glslang::RoundToPow2(currentOffset, 16);
4363
John Kessenich5e4b1242015-08-06 22:53:06 -06004364 nextOffset = currentOffset + memberSize;
4365}
4366
David Netoa901ffe2016-06-08 14:11:40 +01004367void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004368{
David Netoa901ffe2016-06-08 14:11:40 +01004369 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4370 switch (glslangBuiltIn)
4371 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004372 case glslang::EbvPointSize:
4373#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004374 case glslang::EbvClipDistance:
4375 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004376 case glslang::EbvViewportMaskNV:
4377 case glslang::EbvSecondaryPositionNV:
4378 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004379 case glslang::EbvPositionPerViewNV:
4380 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004381 case glslang::EbvTaskCountNV:
4382 case glslang::EbvPrimitiveCountNV:
4383 case glslang::EbvPrimitiveIndicesNV:
4384 case glslang::EbvClipDistancePerViewNV:
4385 case glslang::EbvCullDistancePerViewNV:
4386 case glslang::EbvLayerPerViewNV:
4387 case glslang::EbvMeshViewCountNV:
4388 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004389#endif
David Netoa901ffe2016-06-08 14:11:40 +01004390 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4391 // Alternately, we could just call this for any glslang built-in, since the
4392 // capability already guards against duplicates.
4393 TranslateBuiltInDecoration(glslangBuiltIn, false);
4394 break;
4395 default:
4396 // Capabilities were already generated when the struct was declared.
4397 break;
4398 }
John Kessenichebb50532016-05-16 19:22:05 -06004399}
4400
John Kessenich6fccb3c2016-09-19 16:01:41 -06004401bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004402{
John Kessenicheee9d532016-09-19 18:09:30 -06004403 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004404}
4405
John Kessenichd41993d2017-09-10 15:21:05 -06004406// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004407// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4408// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004409bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004410{
John Kessenich6a14f782017-12-04 02:48:10 -07004411 assert(qualifier == glslang::EvqIn ||
4412 qualifier == glslang::EvqOut ||
4413 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004414 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004415 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004416 return qualifier != glslang::EvqConstReadOnly &&
4417 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004418}
4419
4420// Is parameter pass-by-original?
4421bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4422 bool implicitThisParam)
4423{
4424 if (implicitThisParam) // implicit this
4425 return true;
4426 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004427 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004428 return paramType.containsOpaque() || // sampler, etc.
4429 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4430}
4431
John Kessenich140f3df2015-06-26 16:58:36 -06004432// Make all the functions, skeletally, without actually visiting their bodies.
4433void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4434{
John Kessenich8985fc92020-03-03 10:25:07 -07004435 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4436 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004437 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4438 if (paramPrecision != spv::NoPrecision)
4439 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004440 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004441 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004442 // Original and non-writable params pass the pointer directly and
4443 // use restrict/aliased, others are stored to a pointer in Function
4444 // memory and use RestrictPointer/AliasedPointer.
4445 if (originalParam(type.getQualifier().storage, type, false) ||
4446 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004447 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4448 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004449 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004450 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4451 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004452 }
4453 }
John Kessenichfad62972017-07-18 02:35:46 -06004454 };
4455
John Kessenich140f3df2015-06-26 16:58:36 -06004456 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4457 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004458 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004459 continue;
4460
4461 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004462 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004463 //
qining25262b32016-05-06 17:25:16 -04004464 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004465 // function. What it is an address of varies:
4466 //
John Kessenich4bf71552016-09-02 11:20:21 -06004467 // - "in" parameters not marked as "const" can be written to without modifying the calling
4468 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004469 //
4470 // - "const in" parameters can just be the r-value, as no writes need occur.
4471 //
John Kessenich4bf71552016-09-02 11:20:21 -06004472 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4473 // 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 -06004474
4475 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004476 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004477 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4478
John Kessenich155d3512019-08-08 23:29:20 -06004479#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004480 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4481 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004482#else
4483 bool implicitThis = false;
4484#endif
John Kessenich37789792017-03-21 23:56:40 -06004485
John Kessenichfad62972017-07-18 02:35:46 -06004486 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004487 for (int p = 0; p < (int)parameters.size(); ++p) {
4488 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4489 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004490 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004491 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004492 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004493 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4494 else
John Kessenich4bf71552016-09-02 11:20:21 -06004495 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004496 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004497 paramTypes.push_back(typeId);
4498 }
4499
4500 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004501 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4502 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004503 glslFunction->getName().c_str(), paramTypes,
4504 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004505 if (implicitThis)
4506 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004507
4508 // Track function to emit/call later
4509 functionMap[glslFunction->getName().c_str()] = function;
4510
4511 // Set the parameter id's
4512 for (int p = 0; p < (int)parameters.size(); ++p) {
4513 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4514 // give a name too
4515 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004516
4517 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004518 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004519 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004520 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004521 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004522 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004523 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004524 }
4525 }
4526}
4527
4528// Process all the initializers, while skipping the functions and link objects
4529void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4530{
4531 builder.setBuildPoint(shaderEntry->getLastBlock());
4532 for (int i = 0; i < (int)initializers.size(); ++i) {
4533 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004534 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4535 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004536
4537 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004538 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004539 initializer->traverse(this);
4540 }
4541 }
4542}
4543
4544// Process all the functions, while skipping initializers.
4545void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4546{
4547 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4548 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004549 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004550 node->traverse(this);
4551 }
4552}
4553
4554void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4555{
qining25262b32016-05-06 17:25:16 -04004556 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004557 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004558 currentFunction = functionMap[node->getName().c_str()];
4559 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004560 builder.setBuildPoint(functionBlock);
4561}
4562
John Kessenich8985fc92020-03-03 10:25:07 -07004563void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4564 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004565{
Rex Xufc618912015-09-09 16:42:49 +08004566 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004567
4568 glslang::TSampler sampler = {};
4569 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004570#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004571 bool f16ShadowCompare = false;
4572#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004573 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004574 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4575 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004576#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004577 f16ShadowCompare = sampler.shadow &&
4578 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004579#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004580 }
4581
John Kessenich140f3df2015-06-26 16:58:36 -06004582 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4583 builder.clearAccessChain();
4584 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004585
John Kessenicha28f7a72019-08-06 07:00:58 -06004586#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004587 // Special case l-value operands
4588 bool lvalue = false;
4589 switch (node.getOp()) {
4590 case glslang::EOpImageAtomicAdd:
4591 case glslang::EOpImageAtomicMin:
4592 case glslang::EOpImageAtomicMax:
4593 case glslang::EOpImageAtomicAnd:
4594 case glslang::EOpImageAtomicOr:
4595 case glslang::EOpImageAtomicXor:
4596 case glslang::EOpImageAtomicExchange:
4597 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004598 case glslang::EOpImageAtomicLoad:
4599 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004600 if (i == 0)
4601 lvalue = true;
4602 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004603 case glslang::EOpSparseImageLoad:
4604 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4605 lvalue = true;
4606 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004607 case glslang::EOpSparseTexture:
4608 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4609 lvalue = true;
4610 break;
4611 case glslang::EOpSparseTextureClamp:
4612 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4613 lvalue = true;
4614 break;
4615 case glslang::EOpSparseTextureLod:
4616 case glslang::EOpSparseTextureOffset:
4617 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4618 lvalue = true;
4619 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004620 case glslang::EOpSparseTextureFetch:
4621 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4622 lvalue = true;
4623 break;
4624 case glslang::EOpSparseTextureFetchOffset:
4625 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4626 lvalue = true;
4627 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004628 case glslang::EOpSparseTextureLodOffset:
4629 case glslang::EOpSparseTextureGrad:
4630 case glslang::EOpSparseTextureOffsetClamp:
4631 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4632 lvalue = true;
4633 break;
4634 case glslang::EOpSparseTextureGradOffset:
4635 case glslang::EOpSparseTextureGradClamp:
4636 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4637 lvalue = true;
4638 break;
4639 case glslang::EOpSparseTextureGradOffsetClamp:
4640 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4641 lvalue = true;
4642 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004643 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004644 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4645 lvalue = true;
4646 break;
4647 case glslang::EOpSparseTextureGatherOffset:
4648 case glslang::EOpSparseTextureGatherOffsets:
4649 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4650 lvalue = true;
4651 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004652 case glslang::EOpSparseTextureGatherLod:
4653 if (i == 3)
4654 lvalue = true;
4655 break;
4656 case glslang::EOpSparseTextureGatherLodOffset:
4657 case glslang::EOpSparseTextureGatherLodOffsets:
4658 if (i == 4)
4659 lvalue = true;
4660 break;
Rex Xu129799a2017-07-05 17:23:28 +08004661 case glslang::EOpSparseImageLoadLod:
4662 if (i == 3)
4663 lvalue = true;
4664 break;
Chao Chen3a137962018-09-19 11:41:27 -07004665 case glslang::EOpImageSampleFootprintNV:
4666 if (i == 4)
4667 lvalue = true;
4668 break;
4669 case glslang::EOpImageSampleFootprintClampNV:
4670 case glslang::EOpImageSampleFootprintLodNV:
4671 if (i == 5)
4672 lvalue = true;
4673 break;
4674 case glslang::EOpImageSampleFootprintGradNV:
4675 if (i == 6)
4676 lvalue = true;
4677 break;
4678 case glslang::EOpImageSampleFootprintGradClampNV:
4679 if (i == 7)
4680 lvalue = true;
4681 break;
Rex Xufc618912015-09-09 16:42:49 +08004682 default:
4683 break;
4684 }
4685
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004686 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004687 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004688 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4689 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4690 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004691#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004692 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004693 }
4694}
4695
John Kessenichfc51d282015-08-19 13:34:18 -06004696void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004697{
John Kessenichfc51d282015-08-19 13:34:18 -06004698 builder.clearAccessChain();
4699 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004700 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004701}
John Kessenich140f3df2015-06-26 16:58:36 -06004702
John Kessenichfc51d282015-08-19 13:34:18 -06004703spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4704{
John Kesseniche485c7a2017-05-31 18:50:53 -06004705 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004706 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004707
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004708 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004709
John Kessenichfc51d282015-08-19 13:34:18 -06004710 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004711
John Kessenichf43c7392019-03-31 10:51:57 -06004712 const glslang::TType &imageType = node->getAsAggregate()
4713 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4714 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004715 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004716#ifdef GLSLANG_WEB
4717 const bool f16ShadowCompare = false;
4718#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004719 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004720 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4721 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004722#endif
4723
John Kessenichf43c7392019-03-31 10:51:57 -06004724 const auto signExtensionMask = [&]() {
4725 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4726 if (sampler.type == glslang::EbtUint)
4727 return spv::ImageOperandsZeroExtendMask;
4728 else if (sampler.type == glslang::EbtInt)
4729 return spv::ImageOperandsSignExtendMask;
4730 }
4731 return spv::ImageOperandsMaskNone;
4732 };
4733
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004734 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4735
John Kessenichfc51d282015-08-19 13:34:18 -06004736 std::vector<spv::Id> arguments;
4737 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004738 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004739 else
4740 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004741 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004742
4743 spv::Builder::TextureParameters params = { };
4744 params.sampler = arguments[0];
4745
Rex Xu04db3f52015-09-16 11:44:02 +08004746 glslang::TCrackedTextureOp cracked;
4747 node->crackTexture(sampler, cracked);
4748
amhagan05506bb2017-06-13 16:53:02 -04004749 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004750
John Kessenichfc51d282015-08-19 13:34:18 -06004751 // Check for queries
4752 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004753 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4754 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004755 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004756
John Kessenichfc51d282015-08-19 13:34:18 -06004757 switch (node->getOp()) {
4758 case glslang::EOpImageQuerySize:
4759 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004760 if (arguments.size() > 1) {
4761 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004762 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004763 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004764 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004765#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004766 case glslang::EOpImageQuerySamples:
4767 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004768 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004769 case glslang::EOpTextureQueryLod:
4770 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004771 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004772 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004773 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004774 case glslang::EOpSparseTexelsResident:
4775 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004776#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004777 default:
4778 assert(0);
4779 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004780 }
John Kessenich140f3df2015-06-26 16:58:36 -06004781 }
4782
LoopDawg4425f242018-02-18 11:40:01 -07004783 int components = node->getType().getVectorSize();
4784
4785 if (node->getOp() == glslang::EOpTextureFetch) {
4786 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4787 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4788 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4789 // here around e.g. which ones return scalars or other types.
4790 components = 4;
4791 }
4792
4793 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4794
4795 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4796
Rex Xufc618912015-09-09 16:42:49 +08004797 // Check for image functions other than queries
4798 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004799 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004800 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004801 spv::IdImmediate image = { true, *(opIt++) };
4802 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004803
4804 // Handle subpass operations
4805 // TODO: GLSL should change to have the "MS" only on the type rather than the
4806 // built-in function.
4807 if (cracked.subpass) {
4808 // add on the (0,0) coordinate
4809 spv::Id zero = builder.makeIntConstant(0);
4810 std::vector<spv::Id> comps;
4811 comps.push_back(zero);
4812 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004813 spv::IdImmediate coord = { true,
4814 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4815 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004816 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4817 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004818 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004819 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4820 }
4821 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004822 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004823 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004824 spv::IdImmediate imageOperand = { true, *(opIt++) };
4825 operands.push_back(imageOperand);
4826 }
John Kessenich6c292d32016-02-15 20:58:50 -07004827 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004828 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4829 builder.setPrecision(result, precision);
4830 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004831 }
4832
John Kessenich149afc32018-08-14 13:31:43 -06004833 spv::IdImmediate coord = { true, *(opIt++) };
4834 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004835 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004836 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004837 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004838 mask = mask | spv::ImageOperandsSampleMask;
4839 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004840 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004841 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4842 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004843 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004844 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004845 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4846 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004847 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004848 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004849 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4850 operands.push_back(imageOperands);
4851 }
4852 if (mask & spv::ImageOperandsSampleMask) {
4853 spv::IdImmediate imageOperand = { true, *opIt++ };
4854 operands.push_back(imageOperand);
4855 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004856 if (mask & spv::ImageOperandsLodMask) {
4857 spv::IdImmediate imageOperand = { true, *opIt++ };
4858 operands.push_back(imageOperand);
4859 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004860 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004861 spv::IdImmediate imageOperand = { true,
4862 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004863 operands.push_back(imageOperand);
4864 }
4865
John Kessenich149afc32018-08-14 13:31:43 -06004866 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004867 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004868
John Kessenich149afc32018-08-14 13:31:43 -06004869 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004870 builder.setPrecision(result[0], precision);
4871
4872 // If needed, add a conversion constructor to the proper size.
4873 if (components != node->getType().getVectorSize())
4874 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4875
4876 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004877 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004878
Jeff Bolz36831c92018-09-05 10:11:41 -05004879 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004880 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004881 spv::IdImmediate texel = { true, *(opIt + 1) };
4882 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004883 } else {
4884 spv::IdImmediate texel = { true, *opIt };
4885 operands.push_back(texel);
4886 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004887
4888 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004889 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004890 mask = mask | spv::ImageOperandsSampleMask;
4891 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004892 if (cracked.lod) {
4893 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4894 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4895 mask = mask | spv::ImageOperandsLodMask;
4896 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004897 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4898 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004899 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004900 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004901 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4902 operands.push_back(imageOperands);
4903 }
4904 if (mask & spv::ImageOperandsSampleMask) {
4905 spv::IdImmediate imageOperand = { true, *opIt++ };
4906 operands.push_back(imageOperand);
4907 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004908 if (mask & spv::ImageOperandsLodMask) {
4909 spv::IdImmediate imageOperand = { true, *opIt++ };
4910 operands.push_back(imageOperand);
4911 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004912 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004913 spv::IdImmediate imageOperand = { true,
4914 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004915 operands.push_back(imageOperand);
4916 }
4917
John Kessenich56bab042015-09-16 10:54:31 -06004918 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004919 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004920 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004921 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004922 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4923 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004924 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004925 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004926 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4927
Jeff Bolz36831c92018-09-05 10:11:41 -05004928 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004929 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004930 mask = mask | spv::ImageOperandsSampleMask;
4931 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004932 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004933 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4934 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4935
Jeff Bolz36831c92018-09-05 10:11:41 -05004936 mask = mask | spv::ImageOperandsLodMask;
4937 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004938 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4939 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004940 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004941 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004942 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004943 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004944 }
4945 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004946 spv::IdImmediate imageOperand = { true, *opIt++ };
4947 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004948 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004949 if (mask & spv::ImageOperandsLodMask) {
4950 spv::IdImmediate imageOperand = { true, *opIt++ };
4951 operands.push_back(imageOperand);
4952 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004953 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004954 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4955 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004956 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004957 }
4958
4959 // Create the return type that was a special structure
4960 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004961 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004962 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4963 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4964
4965 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4966
4967 // Decode the return type
4968 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4969 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004970 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004971 // Process image atomic operations
4972
4973 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4974 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004975 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004976 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004977 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004978
Jeff Bolz36831c92018-09-05 10:11:41 -05004979 spv::Id resultTypeId;
4980 // imageAtomicStore has a void return type so base the pointer type on
4981 // the type of the value operand.
4982 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004983 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004984 } else {
4985 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4986 }
John Kessenich56bab042015-09-16 10:54:31 -06004987 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004988 if (imageType.getQualifier().nonUniform) {
4989 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4990 }
Rex Xufc618912015-09-09 16:42:49 +08004991
4992 std::vector<spv::Id> operands;
4993 operands.push_back(pointer);
4994 for (; opIt != arguments.end(); ++opIt)
4995 operands.push_back(*opIt);
4996
John Kessenich8985fc92020-03-03 10:25:07 -07004997 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4998 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004999 }
5000 }
5001
John Kessenicha28f7a72019-08-06 07:00:58 -06005002#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005003 // Check for fragment mask functions other than queries
5004 if (cracked.fragMask) {
5005 assert(sampler.ms);
5006
5007 auto opIt = arguments.begin();
5008 std::vector<spv::Id> operands;
5009
5010 // Extract the image if necessary
5011 if (builder.isSampledImage(params.sampler))
5012 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5013
5014 operands.push_back(params.sampler);
5015 ++opIt;
5016
5017 if (sampler.isSubpass()) {
5018 // add on the (0,0) coordinate
5019 spv::Id zero = builder.makeIntConstant(0);
5020 std::vector<spv::Id> comps;
5021 comps.push_back(zero);
5022 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005023 operands.push_back(builder.makeCompositeConstant(
5024 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005025 }
5026
5027 for (; opIt != arguments.end(); ++opIt)
5028 operands.push_back(*opIt);
5029
5030 spv::Op fragMaskOp = spv::OpNop;
5031 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5032 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5033 else if (node->getOp() == glslang::EOpFragmentFetch)
5034 fragMaskOp = spv::OpFragmentFetchAMD;
5035
5036 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5037 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5038 return builder.createOp(fragMaskOp, resultType(), operands);
5039 }
5040#endif
5041
Rex Xufc618912015-09-09 16:42:49 +08005042 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005043 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005044 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005045 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005046
John Kessenichfc51d282015-08-19 13:34:18 -06005047 // check for bias argument
5048 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005049 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005050 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005051 if (cracked.gather)
5052 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005053
5054 if (f16ShadowCompare)
5055 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005056 if (cracked.offset)
5057 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005058 else if (cracked.offsets)
5059 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005060 if (cracked.grad)
5061 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005062 if (cracked.lodClamp)
5063 ++nonBiasArgCount;
5064 if (sparse)
5065 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005066 if (imageFootprint)
5067 //Following three extra arguments
5068 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5069 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005070 if ((int)arguments.size() > nonBiasArgCount)
5071 bias = true;
5072 }
5073
John Kessenicha5c33d62016-06-02 23:45:21 -06005074 // See if the sampler param should really be just the SPV image part
5075 if (cracked.fetch) {
5076 // a fetch needs to have the image extracted first
5077 if (builder.isSampledImage(params.sampler))
5078 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5079 }
5080
John Kessenicha28f7a72019-08-06 07:00:58 -06005081#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005082 if (cracked.gather) {
5083 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5084 if (bias || cracked.lod ||
5085 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5086 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005087 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005088 }
5089 }
5090#endif
5091
John Kessenichfc51d282015-08-19 13:34:18 -06005092 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005093
John Kessenichfc51d282015-08-19 13:34:18 -06005094 params.coords = arguments[1];
5095 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005096 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005097
5098 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005099 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005100 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005101 ++extraArgs;
5102 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005103 params.Dref = arguments[2];
5104 ++extraArgs;
5105 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005106 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005107 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005108 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005109 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005110 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005111 dRefComp = builder.getNumComponents(params.coords) - 1;
5112 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005113 params.Dref = builder.createCompositeExtract(params.coords,
5114 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005115 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005116
5117 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005118 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005119 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005120 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005121 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5122 !(glslangIntermediate->getStage() == EShLangCompute &&
5123 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005124 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5125 noImplicitLod = true;
5126 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005127
5128 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005129 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005130 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005131 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005132 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005133
5134 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005135 if (cracked.grad) {
5136 params.gradX = arguments[2 + extraArgs];
5137 params.gradY = arguments[3 + extraArgs];
5138 extraArgs += 2;
5139 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005140
5141 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005142 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005143 params.offset = arguments[2 + extraArgs];
5144 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005145 } else if (cracked.offsets) {
5146 params.offsets = arguments[2 + extraArgs];
5147 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005148 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005149
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005150#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005151 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005152 if (cracked.lodClamp) {
5153 params.lodClamp = arguments[2 + extraArgs];
5154 ++extraArgs;
5155 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005156 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005157 if (sparse) {
5158 params.texelOut = arguments[2 + extraArgs];
5159 ++extraArgs;
5160 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005161 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005162 if (cracked.gather && ! sampler.shadow) {
5163 // default component is 0, if missing, otherwise an argument
5164 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005165 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005166 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005167 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005168 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005169 }
Chao Chen3a137962018-09-19 11:41:27 -07005170 spv::Id resultStruct = spv::NoResult;
5171 if (imageFootprint) {
5172 //Following three extra arguments
5173 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5174 params.granularity = arguments[2 + extraArgs];
5175 params.coarse = arguments[3 + extraArgs];
5176 resultStruct = arguments[4 + extraArgs];
5177 extraArgs += 3;
5178 }
5179#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005180 // bias
5181 if (bias) {
5182 params.bias = arguments[2 + extraArgs];
5183 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005184 }
John Kessenichfc51d282015-08-19 13:34:18 -06005185
John Kessenicha28f7a72019-08-06 07:00:58 -06005186#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005187 if (imageFootprint) {
5188 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5189 builder.addCapability(spv::CapabilityImageFootprintNV);
5190
5191
5192 //resultStructType(OpenGL type) contains 5 elements:
5193 //struct gl_TextureFootprint2DNV {
5194 // uvec2 anchor;
5195 // uvec2 offset;
5196 // uvec2 mask;
5197 // uint lod;
5198 // uint granularity;
5199 //};
5200 //or
5201 //struct gl_TextureFootprint3DNV {
5202 // uvec3 anchor;
5203 // uvec3 offset;
5204 // uvec2 mask;
5205 // uint lod;
5206 // uint granularity;
5207 //};
5208 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5209 assert(builder.isStructType(resultStructType));
5210
5211 //resType (SPIR-V type) contains 6 elements:
5212 //Member 0 must be a Boolean type scalar(LOD),
5213 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5214 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5215 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5216 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5217 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5218 std::vector<spv::Id> members;
5219 members.push_back(resultType());
5220 for (int i = 0; i < 5; i++) {
5221 members.push_back(builder.getContainedTypeId(resultStructType, i));
5222 }
5223 spv::Id resType = builder.makeStructType(members, "ResType");
5224
5225 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005226 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5227 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005228
5229 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5230 for (int i = 0; i < 5; i++) {
5231 builder.clearAccessChain();
5232 builder.setAccessChainLValue(resultStruct);
5233
5234 //Accessing to a struct we created, no coherent flag is set
5235 spv::Builder::AccessChain::CoherentFlags flags;
5236 flags.clear();
5237
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005238 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005239 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5240 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005241 }
5242 return builder.createCompositeExtract(res, resultType(), 0);
5243 }
5244#endif
5245
John Kessenich65336482016-06-16 14:06:26 -06005246 // projective component (might not to move)
5247 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5248 // are divided by the last component of P."
5249 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5250 // unused components will appear after all used components."
5251 if (cracked.proj) {
5252 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5253 int projTargetComp;
5254 switch (sampler.dim) {
5255 case glslang::Esd1D: projTargetComp = 1; break;
5256 case glslang::Esd2D: projTargetComp = 2; break;
5257 case glslang::EsdRect: projTargetComp = 2; break;
5258 default: projTargetComp = projSourceComp; break;
5259 }
5260 // copy the projective coordinate if we have to
5261 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005262 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005263 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005264 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005265 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005266 }
5267 }
5268
John Kessenichf8d1d742019-10-21 06:55:11 -06005269#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005270 // nonprivate
5271 if (imageType.getQualifier().nonprivate) {
5272 params.nonprivate = true;
5273 }
5274
5275 // volatile
5276 if (imageType.getQualifier().volatil) {
5277 params.volatil = true;
5278 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005279#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005280
St0fFa1184dd2018-04-09 21:08:14 +02005281 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005282 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5283 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005284 );
LoopDawg4425f242018-02-18 11:40:01 -07005285
5286 if (components != node->getType().getVectorSize())
5287 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5288
5289 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005290}
5291
5292spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5293{
5294 // Grab the function's pointer from the previously created function
5295 spv::Function* function = functionMap[node->getName().c_str()];
5296 if (! function)
5297 return 0;
5298
5299 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5300 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5301
5302 // See comments in makeFunctions() for details about the semantics for parameter passing.
5303 //
5304 // These imply we need a four step process:
5305 // 1. Evaluate the arguments
5306 // 2. Allocate and make copies of in, out, and inout arguments
5307 // 3. Make the call
5308 // 4. Copy back the results
5309
John Kessenichd3ed90b2018-05-04 11:43:03 -06005310 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005311 std::vector<spv::Builder::AccessChain> lValues;
5312 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005313 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005314 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005315 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005316 // build l-value
5317 builder.clearAccessChain();
5318 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005319 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005320 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005321 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005322 // save l-value
5323 lValues.push_back(builder.getAccessChain());
5324 } else {
5325 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005326 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005327 }
5328 }
5329
5330 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5331 // copy the original into that space.
5332 //
5333 // Also, build up the list of actual arguments to pass in for the call
5334 int lValueCount = 0;
5335 int rValueCount = 0;
5336 std::vector<spv::Id> spvArgs;
5337 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5338 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005339 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005340 builder.setAccessChain(lValues[lValueCount]);
5341 arg = builder.accessChainGetLValue();
5342 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005343 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005344 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005345 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005346 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005347 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5348 // need to copy the input into output space
5349 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005350 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005351 builder.clearAccessChain();
5352 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005353 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005354 }
5355 ++lValueCount;
5356 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005357 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005358 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005359 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005360 {
John Kessenich435dd802020-06-30 01:27:08 -06005361 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005362 builder.clearAccessChain();
5363 builder.setAccessChainLValue(argCopy);
5364 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005365 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005366 } else
5367 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005368 ++rValueCount;
5369 }
5370 spvArgs.push_back(arg);
5371 }
5372
5373 // 3. Make the call.
5374 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005375 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005376
5377 // 4. Copy back out an "out" arguments.
5378 lValueCount = 0;
5379 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005380 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005381 ++lValueCount;
5382 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005383 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005384 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005385 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005386 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005387 }
5388 ++lValueCount;
5389 }
5390 }
5391
5392 return result;
5393}
5394
5395// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005396spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005397 spv::Id typeId, spv::Id left, spv::Id right,
5398 glslang::TBasicType typeProxy, bool reduceComparison)
5399{
John Kessenich66011cb2018-03-06 16:12:04 -07005400 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5401 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005402 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005403
5404 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005405 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005406 bool comparison = false;
5407
5408 switch (op) {
5409 case glslang::EOpAdd:
5410 case glslang::EOpAddAssign:
5411 if (isFloat)
5412 binOp = spv::OpFAdd;
5413 else
5414 binOp = spv::OpIAdd;
5415 break;
5416 case glslang::EOpSub:
5417 case glslang::EOpSubAssign:
5418 if (isFloat)
5419 binOp = spv::OpFSub;
5420 else
5421 binOp = spv::OpISub;
5422 break;
5423 case glslang::EOpMul:
5424 case glslang::EOpMulAssign:
5425 if (isFloat)
5426 binOp = spv::OpFMul;
5427 else
5428 binOp = spv::OpIMul;
5429 break;
5430 case glslang::EOpVectorTimesScalar:
5431 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005432 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005433 if (builder.isVector(right))
5434 std::swap(left, right);
5435 assert(builder.isScalar(right));
5436 needMatchingVectors = false;
5437 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005438 } else if (isFloat)
5439 binOp = spv::OpFMul;
5440 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005441 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005442 break;
5443 case glslang::EOpVectorTimesMatrix:
5444 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005445 binOp = spv::OpVectorTimesMatrix;
5446 break;
5447 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005448 binOp = spv::OpMatrixTimesVector;
5449 break;
5450 case glslang::EOpMatrixTimesScalar:
5451 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005452 binOp = spv::OpMatrixTimesScalar;
5453 break;
5454 case glslang::EOpMatrixTimesMatrix:
5455 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005456 binOp = spv::OpMatrixTimesMatrix;
5457 break;
5458 case glslang::EOpOuterProduct:
5459 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005460 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005461 break;
5462
5463 case glslang::EOpDiv:
5464 case glslang::EOpDivAssign:
5465 if (isFloat)
5466 binOp = spv::OpFDiv;
5467 else if (isUnsigned)
5468 binOp = spv::OpUDiv;
5469 else
5470 binOp = spv::OpSDiv;
5471 break;
5472 case glslang::EOpMod:
5473 case glslang::EOpModAssign:
5474 if (isFloat)
5475 binOp = spv::OpFMod;
5476 else if (isUnsigned)
5477 binOp = spv::OpUMod;
5478 else
5479 binOp = spv::OpSMod;
5480 break;
5481 case glslang::EOpRightShift:
5482 case glslang::EOpRightShiftAssign:
5483 if (isUnsigned)
5484 binOp = spv::OpShiftRightLogical;
5485 else
5486 binOp = spv::OpShiftRightArithmetic;
5487 break;
5488 case glslang::EOpLeftShift:
5489 case glslang::EOpLeftShiftAssign:
5490 binOp = spv::OpShiftLeftLogical;
5491 break;
5492 case glslang::EOpAnd:
5493 case glslang::EOpAndAssign:
5494 binOp = spv::OpBitwiseAnd;
5495 break;
5496 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005497 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005498 binOp = spv::OpLogicalAnd;
5499 break;
5500 case glslang::EOpInclusiveOr:
5501 case glslang::EOpInclusiveOrAssign:
5502 binOp = spv::OpBitwiseOr;
5503 break;
5504 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005505 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005506 binOp = spv::OpLogicalOr;
5507 break;
5508 case glslang::EOpExclusiveOr:
5509 case glslang::EOpExclusiveOrAssign:
5510 binOp = spv::OpBitwiseXor;
5511 break;
5512 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005513 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005514 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005515 break;
5516
Ian Romanickb3bd4022019-01-21 08:57:25 -08005517 case glslang::EOpAbsDifference:
5518 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5519 break;
5520
5521 case glslang::EOpAddSaturate:
5522 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5523 break;
5524
5525 case glslang::EOpSubSaturate:
5526 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5527 break;
5528
5529 case glslang::EOpAverage:
5530 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5531 break;
5532
5533 case glslang::EOpAverageRounded:
5534 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5535 break;
5536
5537 case glslang::EOpMul32x16:
5538 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5539 break;
5540
John Kessenich140f3df2015-06-26 16:58:36 -06005541 case glslang::EOpLessThan:
5542 case glslang::EOpGreaterThan:
5543 case glslang::EOpLessThanEqual:
5544 case glslang::EOpGreaterThanEqual:
5545 case glslang::EOpEqual:
5546 case glslang::EOpNotEqual:
5547 case glslang::EOpVectorEqual:
5548 case glslang::EOpVectorNotEqual:
5549 comparison = true;
5550 break;
5551 default:
5552 break;
5553 }
5554
John Kessenich7c1aa102015-10-15 13:29:11 -06005555 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005556 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005557 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005558 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5559 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005560 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005561
5562 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005563 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005564 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005565
qining25262b32016-05-06 17:25:16 -04005566 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005567 decorations.addNoContraction(builder, result);
5568 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005569 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005570 }
5571
5572 if (! comparison)
5573 return 0;
5574
John Kessenich7c1aa102015-10-15 13:29:11 -06005575 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005576
John Kessenich4583b612016-08-07 19:14:22 -06005577 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005578 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5579 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005580 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005581 return result;
5582 }
John Kessenich140f3df2015-06-26 16:58:36 -06005583
5584 switch (op) {
5585 case glslang::EOpLessThan:
5586 if (isFloat)
5587 binOp = spv::OpFOrdLessThan;
5588 else if (isUnsigned)
5589 binOp = spv::OpULessThan;
5590 else
5591 binOp = spv::OpSLessThan;
5592 break;
5593 case glslang::EOpGreaterThan:
5594 if (isFloat)
5595 binOp = spv::OpFOrdGreaterThan;
5596 else if (isUnsigned)
5597 binOp = spv::OpUGreaterThan;
5598 else
5599 binOp = spv::OpSGreaterThan;
5600 break;
5601 case glslang::EOpLessThanEqual:
5602 if (isFloat)
5603 binOp = spv::OpFOrdLessThanEqual;
5604 else if (isUnsigned)
5605 binOp = spv::OpULessThanEqual;
5606 else
5607 binOp = spv::OpSLessThanEqual;
5608 break;
5609 case glslang::EOpGreaterThanEqual:
5610 if (isFloat)
5611 binOp = spv::OpFOrdGreaterThanEqual;
5612 else if (isUnsigned)
5613 binOp = spv::OpUGreaterThanEqual;
5614 else
5615 binOp = spv::OpSGreaterThanEqual;
5616 break;
5617 case glslang::EOpEqual:
5618 case glslang::EOpVectorEqual:
5619 if (isFloat)
5620 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005621 else if (isBool)
5622 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005623 else
5624 binOp = spv::OpIEqual;
5625 break;
5626 case glslang::EOpNotEqual:
5627 case glslang::EOpVectorNotEqual:
5628 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005629 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005630 else if (isBool)
5631 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005632 else
5633 binOp = spv::OpINotEqual;
5634 break;
5635 default:
5636 break;
5637 }
5638
qining25262b32016-05-06 17:25:16 -04005639 if (binOp != spv::OpNop) {
5640 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005641 decorations.addNoContraction(builder, result);
5642 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005643 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005644 }
John Kessenich140f3df2015-06-26 16:58:36 -06005645
5646 return 0;
5647}
5648
John Kessenich04bb8a02015-12-12 12:28:14 -07005649//
5650// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5651// These can be any of:
5652//
5653// matrix * scalar
5654// scalar * matrix
5655// matrix * matrix linear algebraic
5656// matrix * vector
5657// vector * matrix
5658// matrix * matrix componentwise
5659// matrix op matrix op in {+, -, /}
5660// matrix op scalar op in {+, -, /}
5661// scalar op matrix op in {+, -, /}
5662//
John Kessenichead86222018-03-28 18:01:20 -06005663spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5664 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005665{
5666 bool firstClass = true;
5667
5668 // First, handle first-class matrix operations (* and matrix/scalar)
5669 switch (op) {
5670 case spv::OpFDiv:
5671 if (builder.isMatrix(left) && builder.isScalar(right)) {
5672 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005673 spv::Id resultType = builder.getTypeId(right);
5674 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005675 op = spv::OpMatrixTimesScalar;
5676 } else
5677 firstClass = false;
5678 break;
5679 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005680 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005681 std::swap(left, right);
5682 assert(builder.isScalar(right));
5683 break;
5684 case spv::OpVectorTimesMatrix:
5685 assert(builder.isVector(left));
5686 assert(builder.isMatrix(right));
5687 break;
5688 case spv::OpMatrixTimesVector:
5689 assert(builder.isMatrix(left));
5690 assert(builder.isVector(right));
5691 break;
5692 case spv::OpMatrixTimesMatrix:
5693 assert(builder.isMatrix(left));
5694 assert(builder.isMatrix(right));
5695 break;
5696 default:
5697 firstClass = false;
5698 break;
5699 }
5700
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005701 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5702 firstClass = true;
5703
qining25262b32016-05-06 17:25:16 -04005704 if (firstClass) {
5705 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005706 decorations.addNoContraction(builder, result);
5707 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005708 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005709 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005710
LoopDawg592860c2016-06-09 08:57:35 -06005711 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005712 // The result type of all of them is the same type as the (a) matrix operand.
5713 // The algorithm is to:
5714 // - break the matrix(es) into vectors
5715 // - smear any scalar to a vector
5716 // - do vector operations
5717 // - make a matrix out the vector results
5718 switch (op) {
5719 case spv::OpFAdd:
5720 case spv::OpFSub:
5721 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005722 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005723 case spv::OpFMul:
5724 {
5725 // one time set up...
5726 bool leftMat = builder.isMatrix(left);
5727 bool rightMat = builder.isMatrix(right);
5728 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5729 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5730 spv::Id scalarType = builder.getScalarTypeId(typeId);
5731 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5732 std::vector<spv::Id> results;
5733 spv::Id smearVec = spv::NoResult;
5734 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005735 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005736 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005737 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005738
5739 // do each vector op
5740 for (unsigned int c = 0; c < numCols; ++c) {
5741 std::vector<unsigned int> indexes;
5742 indexes.push_back(c);
5743 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5744 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005745 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005746 decorations.addNoContraction(builder, result);
5747 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005748 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005749 }
5750
5751 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005752 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005753 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005754 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005755 }
5756 default:
5757 assert(0);
5758 return spv::NoResult;
5759 }
5760}
5761
John Kessenichead86222018-03-28 18:01:20 -06005762spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005763 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005764{
5765 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005766 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005767 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005768 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5769 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005770
5771 switch (op) {
5772 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005773 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005774 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005775 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005776 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005777 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005778 unaryOp = spv::OpSNegate;
5779 break;
5780
5781 case glslang::EOpLogicalNot:
5782 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005783 unaryOp = spv::OpLogicalNot;
5784 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005785 case glslang::EOpBitwiseNot:
5786 unaryOp = spv::OpNot;
5787 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005788
John Kessenich140f3df2015-06-26 16:58:36 -06005789 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005790 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005791 break;
5792 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005793 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005794 break;
5795 case glslang::EOpTranspose:
5796 unaryOp = spv::OpTranspose;
5797 break;
5798
5799 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005800 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005801 break;
5802 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005803 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005804 break;
5805 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005806 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005807 break;
5808 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005809 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005810 break;
5811 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005812 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005813 break;
5814 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005815 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005816 break;
5817 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005818 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005821 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005822 break;
5823
5824 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005825 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005826 break;
5827 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005828 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005829 break;
5830 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005831 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005832 break;
5833 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005834 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005835 break;
5836 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005837 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005838 break;
5839 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005840 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005841 break;
5842
5843 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005844 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005847 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
5849
5850 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005851 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005852 break;
5853 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005854 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005855 break;
5856 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005857 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005858 break;
5859 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005860 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005861 break;
5862 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005863 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005864 break;
5865 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005866 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005867 break;
5868
5869 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005870 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005871 break;
5872 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005873 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005874 break;
5875 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005876 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005877 break;
5878 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005879 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005880 break;
5881 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005882 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005883 break;
5884 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005885 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005886 break;
5887
5888 case glslang::EOpIsNan:
5889 unaryOp = spv::OpIsNan;
5890 break;
5891 case glslang::EOpIsInf:
5892 unaryOp = spv::OpIsInf;
5893 break;
LoopDawg592860c2016-06-09 08:57:35 -06005894 case glslang::EOpIsFinite:
5895 unaryOp = spv::OpIsFinite;
5896 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005897
Rex Xucbc426e2015-12-15 16:03:10 +08005898 case glslang::EOpFloatBitsToInt:
5899 case glslang::EOpFloatBitsToUint:
5900 case glslang::EOpIntBitsToFloat:
5901 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005902 case glslang::EOpDoubleBitsToInt64:
5903 case glslang::EOpDoubleBitsToUint64:
5904 case glslang::EOpInt64BitsToDouble:
5905 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005906 case glslang::EOpFloat16BitsToInt16:
5907 case glslang::EOpFloat16BitsToUint16:
5908 case glslang::EOpInt16BitsToFloat16:
5909 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005910 unaryOp = spv::OpBitcast;
5911 break;
5912
John Kessenich140f3df2015-06-26 16:58:36 -06005913 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005914 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005915 break;
5916 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005917 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005918 break;
5919 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005920 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005921 break;
5922 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005923 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005924 break;
5925 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005926 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005927 break;
5928 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005929 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005930 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005931#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005932 case glslang::EOpPackSnorm4x8:
5933 libCall = spv::GLSLstd450PackSnorm4x8;
5934 break;
5935 case glslang::EOpUnpackSnorm4x8:
5936 libCall = spv::GLSLstd450UnpackSnorm4x8;
5937 break;
5938 case glslang::EOpPackUnorm4x8:
5939 libCall = spv::GLSLstd450PackUnorm4x8;
5940 break;
5941 case glslang::EOpUnpackUnorm4x8:
5942 libCall = spv::GLSLstd450UnpackUnorm4x8;
5943 break;
5944 case glslang::EOpPackDouble2x32:
5945 libCall = spv::GLSLstd450PackDouble2x32;
5946 break;
5947 case glslang::EOpUnpackDouble2x32:
5948 libCall = spv::GLSLstd450UnpackDouble2x32;
5949 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005950#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005951
Rex Xu8ff43de2016-04-22 16:51:45 +08005952 case glslang::EOpPackInt2x32:
5953 case glslang::EOpUnpackInt2x32:
5954 case glslang::EOpPackUint2x32:
5955 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005956 case glslang::EOpPack16:
5957 case glslang::EOpPack32:
5958 case glslang::EOpPack64:
5959 case glslang::EOpUnpack32:
5960 case glslang::EOpUnpack16:
5961 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005962 case glslang::EOpPackInt2x16:
5963 case glslang::EOpUnpackInt2x16:
5964 case glslang::EOpPackUint2x16:
5965 case glslang::EOpUnpackUint2x16:
5966 case glslang::EOpPackInt4x16:
5967 case glslang::EOpUnpackInt4x16:
5968 case glslang::EOpPackUint4x16:
5969 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005970 case glslang::EOpPackFloat2x16:
5971 case glslang::EOpUnpackFloat2x16:
5972 unaryOp = spv::OpBitcast;
5973 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005974
John Kessenich140f3df2015-06-26 16:58:36 -06005975 case glslang::EOpDPdx:
5976 unaryOp = spv::OpDPdx;
5977 break;
5978 case glslang::EOpDPdy:
5979 unaryOp = spv::OpDPdy;
5980 break;
5981 case glslang::EOpFwidth:
5982 unaryOp = spv::OpFwidth;
5983 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005984
John Kessenich140f3df2015-06-26 16:58:36 -06005985 case glslang::EOpAny:
5986 unaryOp = spv::OpAny;
5987 break;
5988 case glslang::EOpAll:
5989 unaryOp = spv::OpAll;
5990 break;
5991
5992 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005993 if (isFloat)
5994 libCall = spv::GLSLstd450FAbs;
5995 else
5996 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005997 break;
5998 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005999 if (isFloat)
6000 libCall = spv::GLSLstd450FSign;
6001 else
6002 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006003 break;
6004
John Kessenicha28f7a72019-08-06 07:00:58 -06006005#ifndef GLSLANG_WEB
6006 case glslang::EOpDPdxFine:
6007 unaryOp = spv::OpDPdxFine;
6008 break;
6009 case glslang::EOpDPdyFine:
6010 unaryOp = spv::OpDPdyFine;
6011 break;
6012 case glslang::EOpFwidthFine:
6013 unaryOp = spv::OpFwidthFine;
6014 break;
6015 case glslang::EOpDPdxCoarse:
6016 unaryOp = spv::OpDPdxCoarse;
6017 break;
6018 case glslang::EOpDPdyCoarse:
6019 unaryOp = spv::OpDPdyCoarse;
6020 break;
6021 case glslang::EOpFwidthCoarse:
6022 unaryOp = spv::OpFwidthCoarse;
6023 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006024 case glslang::EOpRayQueryProceed:
6025 unaryOp = spv::OpRayQueryProceedKHR;
6026 break;
6027 case glslang::EOpRayQueryGetRayTMin:
6028 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6029 break;
6030 case glslang::EOpRayQueryGetRayFlags:
6031 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6032 break;
6033 case glslang::EOpRayQueryGetWorldRayOrigin:
6034 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6035 break;
6036 case glslang::EOpRayQueryGetWorldRayDirection:
6037 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6038 break;
6039 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6040 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6041 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006042 case glslang::EOpInterpolateAtCentroid:
6043 if (typeProxy == glslang::EbtFloat16)
6044 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6045 libCall = spv::GLSLstd450InterpolateAtCentroid;
6046 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006047 case glslang::EOpAtomicCounterIncrement:
6048 case glslang::EOpAtomicCounterDecrement:
6049 case glslang::EOpAtomicCounter:
6050 {
6051 // Handle all of the atomics in one place, in createAtomicOperation()
6052 std::vector<spv::Id> operands;
6053 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006054 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006055 }
6056
John Kessenichfc51d282015-08-19 13:34:18 -06006057 case glslang::EOpBitFieldReverse:
6058 unaryOp = spv::OpBitReverse;
6059 break;
6060 case glslang::EOpBitCount:
6061 unaryOp = spv::OpBitCount;
6062 break;
6063 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006064 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006065 break;
6066 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006067 if (isUnsigned)
6068 libCall = spv::GLSLstd450FindUMsb;
6069 else
6070 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006071 break;
6072
Ian Romanickb3bd4022019-01-21 08:57:25 -08006073 case glslang::EOpCountLeadingZeros:
6074 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6075 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6076 unaryOp = spv::OpUCountLeadingZerosINTEL;
6077 break;
6078
6079 case glslang::EOpCountTrailingZeros:
6080 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6081 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6082 unaryOp = spv::OpUCountTrailingZerosINTEL;
6083 break;
6084
Rex Xu574ab042016-04-14 16:53:07 +08006085 case glslang::EOpBallot:
6086 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006087 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006088 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006089 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006090 case glslang::EOpMinInvocations:
6091 case glslang::EOpMaxInvocations:
6092 case glslang::EOpAddInvocations:
6093 case glslang::EOpMinInvocationsNonUniform:
6094 case glslang::EOpMaxInvocationsNonUniform:
6095 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006096 case glslang::EOpMinInvocationsInclusiveScan:
6097 case glslang::EOpMaxInvocationsInclusiveScan:
6098 case glslang::EOpAddInvocationsInclusiveScan:
6099 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6100 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6101 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6102 case glslang::EOpMinInvocationsExclusiveScan:
6103 case glslang::EOpMaxInvocationsExclusiveScan:
6104 case glslang::EOpAddInvocationsExclusiveScan:
6105 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6106 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6107 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006108 {
6109 std::vector<spv::Id> operands;
6110 operands.push_back(operand);
6111 return createInvocationsOperation(op, typeId, operands, typeProxy);
6112 }
John Kessenich66011cb2018-03-06 16:12:04 -07006113 case glslang::EOpSubgroupAll:
6114 case glslang::EOpSubgroupAny:
6115 case glslang::EOpSubgroupAllEqual:
6116 case glslang::EOpSubgroupBroadcastFirst:
6117 case glslang::EOpSubgroupBallot:
6118 case glslang::EOpSubgroupInverseBallot:
6119 case glslang::EOpSubgroupBallotBitCount:
6120 case glslang::EOpSubgroupBallotInclusiveBitCount:
6121 case glslang::EOpSubgroupBallotExclusiveBitCount:
6122 case glslang::EOpSubgroupBallotFindLSB:
6123 case glslang::EOpSubgroupBallotFindMSB:
6124 case glslang::EOpSubgroupAdd:
6125 case glslang::EOpSubgroupMul:
6126 case glslang::EOpSubgroupMin:
6127 case glslang::EOpSubgroupMax:
6128 case glslang::EOpSubgroupAnd:
6129 case glslang::EOpSubgroupOr:
6130 case glslang::EOpSubgroupXor:
6131 case glslang::EOpSubgroupInclusiveAdd:
6132 case glslang::EOpSubgroupInclusiveMul:
6133 case glslang::EOpSubgroupInclusiveMin:
6134 case glslang::EOpSubgroupInclusiveMax:
6135 case glslang::EOpSubgroupInclusiveAnd:
6136 case glslang::EOpSubgroupInclusiveOr:
6137 case glslang::EOpSubgroupInclusiveXor:
6138 case glslang::EOpSubgroupExclusiveAdd:
6139 case glslang::EOpSubgroupExclusiveMul:
6140 case glslang::EOpSubgroupExclusiveMin:
6141 case glslang::EOpSubgroupExclusiveMax:
6142 case glslang::EOpSubgroupExclusiveAnd:
6143 case glslang::EOpSubgroupExclusiveOr:
6144 case glslang::EOpSubgroupExclusiveXor:
6145 case glslang::EOpSubgroupQuadSwapHorizontal:
6146 case glslang::EOpSubgroupQuadSwapVertical:
6147 case glslang::EOpSubgroupQuadSwapDiagonal: {
6148 std::vector<spv::Id> operands;
6149 operands.push_back(operand);
6150 return createSubgroupOperation(op, typeId, operands, typeProxy);
6151 }
Rex Xu9d93a232016-05-05 12:30:44 +08006152 case glslang::EOpMbcnt:
6153 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6154 libCall = spv::MbcntAMD;
6155 break;
6156
6157 case glslang::EOpCubeFaceIndex:
6158 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6159 libCall = spv::CubeFaceIndexAMD;
6160 break;
6161
6162 case glslang::EOpCubeFaceCoord:
6163 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6164 libCall = spv::CubeFaceCoordAMD;
6165 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006166 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006167 unaryOp = spv::OpGroupNonUniformPartitionNV;
6168 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006169 case glslang::EOpConstructReference:
6170 unaryOp = spv::OpBitcast;
6171 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006172#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006173
6174 case glslang::EOpCopyObject:
6175 unaryOp = spv::OpCopyObject;
6176 break;
6177
John Kessenich140f3df2015-06-26 16:58:36 -06006178 default:
6179 return 0;
6180 }
6181
6182 spv::Id id;
6183 if (libCall >= 0) {
6184 std::vector<spv::Id> args;
6185 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006186 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006187 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006188 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006189 }
John Kessenich140f3df2015-06-26 16:58:36 -06006190
John Kessenichb9197c82019-08-11 07:41:45 -06006191 decorations.addNoContraction(builder, id);
6192 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006193 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006194}
6195
John Kessenich7a53f762016-01-20 11:19:27 -07006196// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006197spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6198 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006199{
6200 // Handle unary operations vector by vector.
6201 // The result type is the same type as the original type.
6202 // The algorithm is to:
6203 // - break the matrix into vectors
6204 // - apply the operation to each vector
6205 // - make a matrix out the vector results
6206
6207 // get the types sorted out
6208 int numCols = builder.getNumColumns(operand);
6209 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006210 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6211 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006212 std::vector<spv::Id> results;
6213
6214 // do each vector op
6215 for (int c = 0; c < numCols; ++c) {
6216 std::vector<unsigned int> indexes;
6217 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006218 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6219 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006220 decorations.addNoContraction(builder, destVec);
6221 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006222 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006223 }
6224
6225 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006226 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006227 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006228 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006229}
6230
John Kessenichad7645f2018-06-04 19:11:25 -06006231// For converting integers where both the bitwidth and the signedness could
6232// change, but only do the width change here. The caller is still responsible
6233// for the signedness conversion.
6234spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006235{
John Kessenichad7645f2018-06-04 19:11:25 -06006236 // Get the result type width, based on the type to convert to.
6237 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006238 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006239 case glslang::EOpConvInt16ToUint8:
6240 case glslang::EOpConvIntToUint8:
6241 case glslang::EOpConvInt64ToUint8:
6242 case glslang::EOpConvUint16ToInt8:
6243 case glslang::EOpConvUintToInt8:
6244 case glslang::EOpConvUint64ToInt8:
6245 width = 8;
6246 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006247 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006248 case glslang::EOpConvIntToUint16:
6249 case glslang::EOpConvInt64ToUint16:
6250 case glslang::EOpConvUint8ToInt16:
6251 case glslang::EOpConvUintToInt16:
6252 case glslang::EOpConvUint64ToInt16:
6253 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006254 break;
6255 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006256 case glslang::EOpConvInt16ToUint:
6257 case glslang::EOpConvInt64ToUint:
6258 case glslang::EOpConvUint8ToInt:
6259 case glslang::EOpConvUint16ToInt:
6260 case glslang::EOpConvUint64ToInt:
6261 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006262 break;
6263 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006264 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006265 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006266 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006267 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006268 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006269 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006270 break;
6271
6272 default:
6273 assert(false && "Default missing");
6274 break;
6275 }
6276
John Kessenichad7645f2018-06-04 19:11:25 -06006277 // Get the conversion operation and result type,
6278 // based on the target width, but the source type.
6279 spv::Id type = spv::NoType;
6280 spv::Op convOp = spv::OpNop;
6281 switch(op) {
6282 case glslang::EOpConvInt8ToUint16:
6283 case glslang::EOpConvInt8ToUint:
6284 case glslang::EOpConvInt8ToUint64:
6285 case glslang::EOpConvInt16ToUint8:
6286 case glslang::EOpConvInt16ToUint:
6287 case glslang::EOpConvInt16ToUint64:
6288 case glslang::EOpConvIntToUint8:
6289 case glslang::EOpConvIntToUint16:
6290 case glslang::EOpConvIntToUint64:
6291 case glslang::EOpConvInt64ToUint8:
6292 case glslang::EOpConvInt64ToUint16:
6293 case glslang::EOpConvInt64ToUint:
6294 convOp = spv::OpSConvert;
6295 type = builder.makeIntType(width);
6296 break;
6297 default:
6298 convOp = spv::OpUConvert;
6299 type = builder.makeUintType(width);
6300 break;
6301 }
6302
John Kessenich66011cb2018-03-06 16:12:04 -07006303 if (vectorSize > 0)
6304 type = builder.makeVectorType(type, vectorSize);
6305
John Kessenichad7645f2018-06-04 19:11:25 -06006306 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006307}
6308
John Kessenichead86222018-03-28 18:01:20 -06006309spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6310 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006311{
6312 spv::Op convOp = spv::OpNop;
6313 spv::Id zero = 0;
6314 spv::Id one = 0;
6315
6316 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6317
6318 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006319 case glslang::EOpConvIntToBool:
6320 case glslang::EOpConvUintToBool:
6321 zero = builder.makeUintConstant(0);
6322 zero = makeSmearedConstant(zero, vectorSize);
6323 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006324 case glslang::EOpConvFloatToBool:
6325 zero = builder.makeFloatConstant(0.0F);
6326 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006327 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006328 case glslang::EOpConvBoolToFloat:
6329 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006330 zero = builder.makeFloatConstant(0.0F);
6331 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006332 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006333
John Kessenich140f3df2015-06-26 16:58:36 -06006334 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006335 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006336#ifndef GLSLANG_WEB
6337 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006338 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006339 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006340 } else
6341#endif
6342 {
6343 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006344 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006345 }
Rex Xucabbb782017-03-24 13:41:14 +08006346
John Kessenich140f3df2015-06-26 16:58:36 -06006347 convOp = spv::OpSelect;
6348 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006349
John Kessenich140f3df2015-06-26 16:58:36 -06006350 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006351 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006352#ifndef GLSLANG_WEB
6353 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006354 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006355 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006356 } else
6357#endif
6358 {
6359 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006360 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006361 }
Rex Xucabbb782017-03-24 13:41:14 +08006362
John Kessenich140f3df2015-06-26 16:58:36 -06006363 convOp = spv::OpSelect;
6364 break;
6365
John Kessenich66011cb2018-03-06 16:12:04 -07006366 case glslang::EOpConvInt8ToFloat16:
6367 case glslang::EOpConvInt8ToFloat:
6368 case glslang::EOpConvInt8ToDouble:
6369 case glslang::EOpConvInt16ToFloat16:
6370 case glslang::EOpConvInt16ToFloat:
6371 case glslang::EOpConvInt16ToDouble:
6372 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006373 case glslang::EOpConvIntToFloat:
6374 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006375 case glslang::EOpConvInt64ToFloat:
6376 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006377 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006378 convOp = spv::OpConvertSToF;
6379 break;
6380
John Kessenich66011cb2018-03-06 16:12:04 -07006381 case glslang::EOpConvUint8ToFloat16:
6382 case glslang::EOpConvUint8ToFloat:
6383 case glslang::EOpConvUint8ToDouble:
6384 case glslang::EOpConvUint16ToFloat16:
6385 case glslang::EOpConvUint16ToFloat:
6386 case glslang::EOpConvUint16ToDouble:
6387 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006388 case glslang::EOpConvUintToFloat:
6389 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006390 case glslang::EOpConvUint64ToFloat:
6391 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006392 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006393 convOp = spv::OpConvertUToF;
6394 break;
6395
John Kessenich66011cb2018-03-06 16:12:04 -07006396 case glslang::EOpConvFloat16ToInt8:
6397 case glslang::EOpConvFloatToInt8:
6398 case glslang::EOpConvDoubleToInt8:
6399 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006400 case glslang::EOpConvFloatToInt16:
6401 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006402 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006403 case glslang::EOpConvFloatToInt:
6404 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006405 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006406 case glslang::EOpConvFloatToInt64:
6407 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006408 convOp = spv::OpConvertFToS;
6409 break;
6410
John Kessenich66011cb2018-03-06 16:12:04 -07006411 case glslang::EOpConvUint8ToInt8:
6412 case glslang::EOpConvInt8ToUint8:
6413 case glslang::EOpConvUint16ToInt16:
6414 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006415 case glslang::EOpConvUintToInt:
6416 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006417 case glslang::EOpConvUint64ToInt64:
6418 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006419 if (builder.isInSpecConstCodeGenMode()) {
6420 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006421#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006422 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6423 zero = builder.makeUint8Constant(0);
6424 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006425 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006426 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6427 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006428 } else
6429#endif
6430 {
Rex Xucabbb782017-03-24 13:41:14 +08006431 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006432 }
qining189b2032016-04-12 23:16:20 -04006433 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006434 // Use OpIAdd, instead of OpBitcast to do the conversion when
6435 // generating for OpSpecConstantOp instruction.
6436 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6437 }
6438 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006439 convOp = spv::OpBitcast;
6440 break;
6441
John Kessenich66011cb2018-03-06 16:12:04 -07006442 case glslang::EOpConvFloat16ToUint8:
6443 case glslang::EOpConvFloatToUint8:
6444 case glslang::EOpConvDoubleToUint8:
6445 case glslang::EOpConvFloat16ToUint16:
6446 case glslang::EOpConvFloatToUint16:
6447 case glslang::EOpConvDoubleToUint16:
6448 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006449 case glslang::EOpConvFloatToUint:
6450 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006451 case glslang::EOpConvFloatToUint64:
6452 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006453 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006454 convOp = spv::OpConvertFToU;
6455 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006456
John Kessenich39697cd2019-08-08 10:35:51 -06006457#ifndef GLSLANG_WEB
6458 case glslang::EOpConvInt8ToBool:
6459 case glslang::EOpConvUint8ToBool:
6460 zero = builder.makeUint8Constant(0);
6461 zero = makeSmearedConstant(zero, vectorSize);
6462 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6463 case glslang::EOpConvInt16ToBool:
6464 case glslang::EOpConvUint16ToBool:
6465 zero = builder.makeUint16Constant(0);
6466 zero = makeSmearedConstant(zero, vectorSize);
6467 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6468 case glslang::EOpConvInt64ToBool:
6469 case glslang::EOpConvUint64ToBool:
6470 zero = builder.makeUint64Constant(0);
6471 zero = makeSmearedConstant(zero, vectorSize);
6472 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6473 case glslang::EOpConvDoubleToBool:
6474 zero = builder.makeDoubleConstant(0.0);
6475 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006476 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006477 case glslang::EOpConvFloat16ToBool:
6478 zero = builder.makeFloat16Constant(0.0F);
6479 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006480 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006481 case glslang::EOpConvBoolToDouble:
6482 convOp = spv::OpSelect;
6483 zero = builder.makeDoubleConstant(0.0);
6484 one = builder.makeDoubleConstant(1.0);
6485 break;
6486 case glslang::EOpConvBoolToFloat16:
6487 convOp = spv::OpSelect;
6488 zero = builder.makeFloat16Constant(0.0F);
6489 one = builder.makeFloat16Constant(1.0F);
6490 break;
6491 case glslang::EOpConvBoolToInt8:
6492 zero = builder.makeInt8Constant(0);
6493 one = builder.makeInt8Constant(1);
6494 convOp = spv::OpSelect;
6495 break;
6496 case glslang::EOpConvBoolToUint8:
6497 zero = builder.makeUint8Constant(0);
6498 one = builder.makeUint8Constant(1);
6499 convOp = spv::OpSelect;
6500 break;
6501 case glslang::EOpConvBoolToInt16:
6502 zero = builder.makeInt16Constant(0);
6503 one = builder.makeInt16Constant(1);
6504 convOp = spv::OpSelect;
6505 break;
6506 case glslang::EOpConvBoolToUint16:
6507 zero = builder.makeUint16Constant(0);
6508 one = builder.makeUint16Constant(1);
6509 convOp = spv::OpSelect;
6510 break;
6511 case glslang::EOpConvDoubleToFloat:
6512 case glslang::EOpConvFloatToDouble:
6513 case glslang::EOpConvDoubleToFloat16:
6514 case glslang::EOpConvFloat16ToDouble:
6515 case glslang::EOpConvFloatToFloat16:
6516 case glslang::EOpConvFloat16ToFloat:
6517 convOp = spv::OpFConvert;
6518 if (builder.isMatrixType(destType))
6519 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6520 break;
6521
John Kessenich66011cb2018-03-06 16:12:04 -07006522 case glslang::EOpConvInt8ToInt16:
6523 case glslang::EOpConvInt8ToInt:
6524 case glslang::EOpConvInt8ToInt64:
6525 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006526 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006527 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006528 case glslang::EOpConvIntToInt8:
6529 case glslang::EOpConvIntToInt16:
6530 case glslang::EOpConvIntToInt64:
6531 case glslang::EOpConvInt64ToInt8:
6532 case glslang::EOpConvInt64ToInt16:
6533 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006534 convOp = spv::OpSConvert;
6535 break;
6536
John Kessenich66011cb2018-03-06 16:12:04 -07006537 case glslang::EOpConvUint8ToUint16:
6538 case glslang::EOpConvUint8ToUint:
6539 case glslang::EOpConvUint8ToUint64:
6540 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006541 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006542 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006543 case glslang::EOpConvUintToUint8:
6544 case glslang::EOpConvUintToUint16:
6545 case glslang::EOpConvUintToUint64:
6546 case glslang::EOpConvUint64ToUint8:
6547 case glslang::EOpConvUint64ToUint16:
6548 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006549 convOp = spv::OpUConvert;
6550 break;
6551
John Kessenich66011cb2018-03-06 16:12:04 -07006552 case glslang::EOpConvInt8ToUint16:
6553 case glslang::EOpConvInt8ToUint:
6554 case glslang::EOpConvInt8ToUint64:
6555 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006556 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006557 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006558 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006559 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006560 case glslang::EOpConvIntToUint64:
6561 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006562 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006563 case glslang::EOpConvInt64ToUint:
6564 case glslang::EOpConvUint8ToInt16:
6565 case glslang::EOpConvUint8ToInt:
6566 case glslang::EOpConvUint8ToInt64:
6567 case glslang::EOpConvUint16ToInt8:
6568 case glslang::EOpConvUint16ToInt:
6569 case glslang::EOpConvUint16ToInt64:
6570 case glslang::EOpConvUintToInt8:
6571 case glslang::EOpConvUintToInt16:
6572 case glslang::EOpConvUintToInt64:
6573 case glslang::EOpConvUint64ToInt8:
6574 case glslang::EOpConvUint64ToInt16:
6575 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006576 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006577 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006578
6579 if (builder.isInSpecConstCodeGenMode()) {
6580 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006581 switch(op) {
6582 case glslang::EOpConvInt16ToUint8:
6583 case glslang::EOpConvIntToUint8:
6584 case glslang::EOpConvInt64ToUint8:
6585 case glslang::EOpConvUint16ToInt8:
6586 case glslang::EOpConvUintToInt8:
6587 case glslang::EOpConvUint64ToInt8:
6588 zero = builder.makeUint8Constant(0);
6589 break;
6590 case glslang::EOpConvInt8ToUint16:
6591 case glslang::EOpConvIntToUint16:
6592 case glslang::EOpConvInt64ToUint16:
6593 case glslang::EOpConvUint8ToInt16:
6594 case glslang::EOpConvUintToInt16:
6595 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006596 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006597 break;
6598 case glslang::EOpConvInt8ToUint:
6599 case glslang::EOpConvInt16ToUint:
6600 case glslang::EOpConvInt64ToUint:
6601 case glslang::EOpConvUint8ToInt:
6602 case glslang::EOpConvUint16ToInt:
6603 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006604 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006605 break;
6606 case glslang::EOpConvInt8ToUint64:
6607 case glslang::EOpConvInt16ToUint64:
6608 case glslang::EOpConvIntToUint64:
6609 case glslang::EOpConvUint8ToInt64:
6610 case glslang::EOpConvUint16ToInt64:
6611 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006612 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006613 break;
6614 default:
6615 assert(false && "Default missing");
6616 break;
6617 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006618 zero = makeSmearedConstant(zero, vectorSize);
6619 // Use OpIAdd, instead of OpBitcast to do the conversion when
6620 // generating for OpSpecConstantOp instruction.
6621 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6622 }
6623 // For normal run-time conversion instruction, use OpBitcast.
6624 convOp = spv::OpBitcast;
6625 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006626 case glslang::EOpConvUint64ToPtr:
6627 convOp = spv::OpConvertUToPtr;
6628 break;
6629 case glslang::EOpConvPtrToUint64:
6630 convOp = spv::OpConvertPtrToU;
6631 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006632 case glslang::EOpConvPtrToUvec2:
6633 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006634 if (builder.isVector(operand))
6635 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6636 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006637 convOp = spv::OpBitcast;
6638 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006639#endif
6640
John Kessenich140f3df2015-06-26 16:58:36 -06006641 default:
6642 break;
6643 }
6644
6645 spv::Id result = 0;
6646 if (convOp == spv::OpNop)
6647 return result;
6648
6649 if (convOp == spv::OpSelect) {
6650 zero = makeSmearedConstant(zero, vectorSize);
6651 one = makeSmearedConstant(one, vectorSize);
6652 result = builder.createTriOp(convOp, destType, operand, one, zero);
6653 } else
6654 result = builder.createUnaryOp(convOp, destType, operand);
6655
John Kessenichead86222018-03-28 18:01:20 -06006656 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006657 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006658 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006659}
6660
6661spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6662{
6663 if (vectorSize == 0)
6664 return constant;
6665
6666 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6667 std::vector<spv::Id> components;
6668 for (int c = 0; c < vectorSize; ++c)
6669 components.push_back(constant);
6670 return builder.makeCompositeConstant(vectorTypeId, components);
6671}
6672
John Kessenich426394d2015-07-23 10:22:48 -06006673// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006674spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6675 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6676 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006677{
6678 spv::Op opCode = spv::OpNop;
6679
6680 switch (op) {
6681 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006682 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006683 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006684 opCode = spv::OpAtomicIAdd;
6685 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006686 case glslang::EOpAtomicCounterSubtract:
6687 opCode = spv::OpAtomicISub;
6688 break;
John Kessenich426394d2015-07-23 10:22:48 -06006689 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006690 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006691 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006692 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6693 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006694 break;
6695 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006696 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006697 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006698 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6699 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006700 break;
6701 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006702 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006703 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006704 opCode = spv::OpAtomicAnd;
6705 break;
6706 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006707 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006708 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006709 opCode = spv::OpAtomicOr;
6710 break;
6711 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006712 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006713 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006714 opCode = spv::OpAtomicXor;
6715 break;
6716 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006717 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006718 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006719 opCode = spv::OpAtomicExchange;
6720 break;
6721 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006722 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006723 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006724 opCode = spv::OpAtomicCompareExchange;
6725 break;
6726 case glslang::EOpAtomicCounterIncrement:
6727 opCode = spv::OpAtomicIIncrement;
6728 break;
6729 case glslang::EOpAtomicCounterDecrement:
6730 opCode = spv::OpAtomicIDecrement;
6731 break;
6732 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006733 case glslang::EOpImageAtomicLoad:
6734 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006735 opCode = spv::OpAtomicLoad;
6736 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006737 case glslang::EOpAtomicStore:
6738 case glslang::EOpImageAtomicStore:
6739 opCode = spv::OpAtomicStore;
6740 break;
John Kessenich426394d2015-07-23 10:22:48 -06006741 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006742 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006743 break;
6744 }
6745
Rex Xue8fe8b02017-09-26 15:42:56 +08006746 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6747 builder.addCapability(spv::CapabilityInt64Atomics);
6748
John Kessenich426394d2015-07-23 10:22:48 -06006749 // Sort out the operands
6750 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006751 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006752 // - compare-exchange swaps the value and comparator
6753 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006754 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006755 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6756 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6757 spv::Id scopeId;
6758 if (glslangIntermediate->usingVulkanMemoryModel()) {
6759 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6760 } else {
6761 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6762 }
6763 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006764 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6765 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006766 spv::MemorySemanticsVolatileMask :
6767 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006768 spv::Id semanticsId2 = semanticsId;
6769
6770 pointerId = operands[0];
6771 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6772 // no additional operands
6773 } else if (opCode == spv::OpAtomicCompareExchange) {
6774 compareId = operands[1];
6775 valueId = operands[2];
6776 if (operands.size() > 3) {
6777 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006778 semanticsId = builder.makeUintConstant(
6779 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6780 semanticsId2 = builder.makeUintConstant(
6781 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006782 }
6783 } else if (opCode == spv::OpAtomicLoad) {
6784 if (operands.size() > 1) {
6785 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006786 semanticsId = builder.makeUintConstant(
6787 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006788 }
6789 } else {
6790 // atomic store or RMW
6791 valueId = operands[1];
6792 if (operands.size() > 2) {
6793 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006794 semanticsId = builder.makeUintConstant
6795 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006796 }
Rex Xu04db3f52015-09-16 11:44:02 +08006797 }
John Kessenich426394d2015-07-23 10:22:48 -06006798
Jeff Bolz36831c92018-09-05 10:11:41 -05006799 // Check for capabilities
6800 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006801 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6802 spv::MemorySemanticsMakeVisibleKHRMask |
6803 spv::MemorySemanticsOutputMemoryKHRMask |
6804 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006805 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6806 }
John Kessenich426394d2015-07-23 10:22:48 -06006807
Jeff Bolz36831c92018-09-05 10:11:41 -05006808 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6809 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6810 }
John Kessenich48d6e792017-10-06 21:21:48 -06006811
Jeff Bolz36831c92018-09-05 10:11:41 -05006812 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6813 spvAtomicOperands.push_back(pointerId);
6814 spvAtomicOperands.push_back(scopeId);
6815 spvAtomicOperands.push_back(semanticsId);
6816 if (opCode == spv::OpAtomicCompareExchange) {
6817 spvAtomicOperands.push_back(semanticsId2);
6818 spvAtomicOperands.push_back(valueId);
6819 spvAtomicOperands.push_back(compareId);
6820 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6821 spvAtomicOperands.push_back(valueId);
6822 }
John Kessenich48d6e792017-10-06 21:21:48 -06006823
Jeff Bolz36831c92018-09-05 10:11:41 -05006824 if (opCode == spv::OpAtomicStore) {
6825 builder.createNoResultOp(opCode, spvAtomicOperands);
6826 return 0;
6827 } else {
6828 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6829
6830 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6831 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6832 if (op == glslang::EOpAtomicCounterDecrement)
6833 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6834
6835 return resultId;
6836 }
John Kessenich426394d2015-07-23 10:22:48 -06006837}
6838
John Kessenich91cef522016-05-05 16:45:40 -06006839// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006840spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6841 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006842{
John Kessenich66011cb2018-03-06 16:12:04 -07006843 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6844 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006845
Rex Xu51596642016-09-21 18:56:12 +08006846 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006847 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006848 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6849
chaocf200da82016-12-20 12:44:35 -08006850 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6851 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006852 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6853 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006854 } else if (op == glslang::EOpAnyInvocation ||
6855 op == glslang::EOpAllInvocations ||
6856 op == glslang::EOpAllInvocationsEqual) {
6857 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6858 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006859 } else {
6860 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006861 if (op == glslang::EOpMinInvocationsNonUniform ||
6862 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006863 op == glslang::EOpAddInvocationsNonUniform ||
6864 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6865 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6866 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6867 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6868 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6869 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006870 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006871
Rex Xu430ef402016-10-14 17:22:23 +08006872 switch (op) {
6873 case glslang::EOpMinInvocations:
6874 case glslang::EOpMaxInvocations:
6875 case glslang::EOpAddInvocations:
6876 case glslang::EOpMinInvocationsNonUniform:
6877 case glslang::EOpMaxInvocationsNonUniform:
6878 case glslang::EOpAddInvocationsNonUniform:
6879 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006880 break;
6881 case glslang::EOpMinInvocationsInclusiveScan:
6882 case glslang::EOpMaxInvocationsInclusiveScan:
6883 case glslang::EOpAddInvocationsInclusiveScan:
6884 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6885 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6886 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6887 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006888 break;
6889 case glslang::EOpMinInvocationsExclusiveScan:
6890 case glslang::EOpMaxInvocationsExclusiveScan:
6891 case glslang::EOpAddInvocationsExclusiveScan:
6892 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6893 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6894 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6895 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006896 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006897 default:
6898 break;
Rex Xu430ef402016-10-14 17:22:23 +08006899 }
John Kessenich149afc32018-08-14 13:31:43 -06006900 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6901 spvGroupOperands.push_back(scope);
6902 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006903 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006904 spvGroupOperands.push_back(groupOp);
6905 }
Rex Xu51596642016-09-21 18:56:12 +08006906 }
6907
John Kessenich149afc32018-08-14 13:31:43 -06006908 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6909 spv::IdImmediate op = { true, *opIt };
6910 spvGroupOperands.push_back(op);
6911 }
John Kessenich91cef522016-05-05 16:45:40 -06006912
6913 switch (op) {
6914 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006915 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006916 break;
John Kessenich91cef522016-05-05 16:45:40 -06006917 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006918 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006919 break;
John Kessenich91cef522016-05-05 16:45:40 -06006920 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006921 opCode = spv::OpSubgroupAllEqualKHR;
6922 break;
Rex Xu51596642016-09-21 18:56:12 +08006923 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006924 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006925 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006926 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006927 break;
6928 case glslang::EOpReadFirstInvocation:
6929 opCode = spv::OpSubgroupFirstInvocationKHR;
6930 break;
6931 case glslang::EOpBallot:
6932 {
6933 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6934 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6935 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6936 //
6937 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6938 //
6939 spv::Id uintType = builder.makeUintType(32);
6940 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6941 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6942
6943 std::vector<spv::Id> components;
6944 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6945 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6946
6947 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6948 return builder.createUnaryOp(spv::OpBitcast, typeId,
6949 builder.createCompositeConstruct(uvec2Type, components));
6950 }
6951
Rex Xu9d93a232016-05-05 12:30:44 +08006952 case glslang::EOpMinInvocations:
6953 case glslang::EOpMaxInvocations:
6954 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006955 case glslang::EOpMinInvocationsInclusiveScan:
6956 case glslang::EOpMaxInvocationsInclusiveScan:
6957 case glslang::EOpAddInvocationsInclusiveScan:
6958 case glslang::EOpMinInvocationsExclusiveScan:
6959 case glslang::EOpMaxInvocationsExclusiveScan:
6960 case glslang::EOpAddInvocationsExclusiveScan:
6961 if (op == glslang::EOpMinInvocations ||
6962 op == glslang::EOpMinInvocationsInclusiveScan ||
6963 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006964 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006965 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006966 else {
6967 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006968 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006969 else
Rex Xu51596642016-09-21 18:56:12 +08006970 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006971 }
Rex Xu430ef402016-10-14 17:22:23 +08006972 } else if (op == glslang::EOpMaxInvocations ||
6973 op == glslang::EOpMaxInvocationsInclusiveScan ||
6974 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006975 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006976 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006977 else {
6978 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006979 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006980 else
Rex Xu51596642016-09-21 18:56:12 +08006981 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006982 }
6983 } else {
6984 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006985 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006986 else
Rex Xu51596642016-09-21 18:56:12 +08006987 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006988 }
6989
Rex Xu2bbbe062016-08-23 15:41:05 +08006990 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006991 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006992
6993 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006994 case glslang::EOpMinInvocationsNonUniform:
6995 case glslang::EOpMaxInvocationsNonUniform:
6996 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006997 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6998 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6999 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7000 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7001 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7002 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7003 if (op == glslang::EOpMinInvocationsNonUniform ||
7004 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7005 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007006 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007007 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007008 else {
7009 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007010 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007011 else
Rex Xu51596642016-09-21 18:56:12 +08007012 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007013 }
7014 }
Rex Xu430ef402016-10-14 17:22:23 +08007015 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7016 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7017 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007018 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007019 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007020 else {
7021 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007022 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007023 else
Rex Xu51596642016-09-21 18:56:12 +08007024 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007025 }
7026 }
7027 else {
7028 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007029 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007030 else
Rex Xu51596642016-09-21 18:56:12 +08007031 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007032 }
7033
Rex Xu2bbbe062016-08-23 15:41:05 +08007034 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007035 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007036
7037 break;
John Kessenich91cef522016-05-05 16:45:40 -06007038 default:
7039 logger->missingFunctionality("invocation operation");
7040 return spv::NoResult;
7041 }
Rex Xu51596642016-09-21 18:56:12 +08007042
7043 assert(opCode != spv::OpNop);
7044 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007045}
7046
Rex Xu2bbbe062016-08-23 15:41:05 +08007047// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007048spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7049 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007050{
7051 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7052 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007053 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007054 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007055 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7056 op == spv::OpGroupSMinNonUniformAMD ||
7057 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7058 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007059 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7060
7061 // Handle group invocation operations scalar by scalar.
7062 // The result type is the same type as the original type.
7063 // The algorithm is to:
7064 // - break the vector into scalars
7065 // - apply the operation to each scalar
7066 // - make a vector out the scalar results
7067
7068 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007069 int numComponents = builder.getNumComponents(operands[0]);
7070 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007071 std::vector<spv::Id> results;
7072
7073 // do each scalar op
7074 for (int comp = 0; comp < numComponents; ++comp) {
7075 std::vector<unsigned int> indexes;
7076 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007077 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7078 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007079 if (op == spv::OpSubgroupReadInvocationKHR) {
7080 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007081 spv::IdImmediate operand = { true, operands[1] };
7082 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007083 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007084 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7085 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007086 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007087 spv::IdImmediate operand = { true, operands[1] };
7088 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007089 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007090 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7091 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007092 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007093 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007094 spvGroupOperands.push_back(scalar);
7095 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007096
Rex Xub7072052016-09-26 15:53:40 +08007097 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007098 }
7099
7100 // put the pieces together
7101 return builder.createCompositeConstruct(typeId, results);
7102}
Rex Xu2bbbe062016-08-23 15:41:05 +08007103
John Kessenich66011cb2018-03-06 16:12:04 -07007104// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007105spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7106 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007107{
7108 // Add the required capabilities.
7109 switch (op) {
7110 case glslang::EOpSubgroupElect:
7111 builder.addCapability(spv::CapabilityGroupNonUniform);
7112 break;
7113 case glslang::EOpSubgroupAll:
7114 case glslang::EOpSubgroupAny:
7115 case glslang::EOpSubgroupAllEqual:
7116 builder.addCapability(spv::CapabilityGroupNonUniform);
7117 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7118 break;
7119 case glslang::EOpSubgroupBroadcast:
7120 case glslang::EOpSubgroupBroadcastFirst:
7121 case glslang::EOpSubgroupBallot:
7122 case glslang::EOpSubgroupInverseBallot:
7123 case glslang::EOpSubgroupBallotBitExtract:
7124 case glslang::EOpSubgroupBallotBitCount:
7125 case glslang::EOpSubgroupBallotInclusiveBitCount:
7126 case glslang::EOpSubgroupBallotExclusiveBitCount:
7127 case glslang::EOpSubgroupBallotFindLSB:
7128 case glslang::EOpSubgroupBallotFindMSB:
7129 builder.addCapability(spv::CapabilityGroupNonUniform);
7130 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7131 break;
7132 case glslang::EOpSubgroupShuffle:
7133 case glslang::EOpSubgroupShuffleXor:
7134 builder.addCapability(spv::CapabilityGroupNonUniform);
7135 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7136 break;
7137 case glslang::EOpSubgroupShuffleUp:
7138 case glslang::EOpSubgroupShuffleDown:
7139 builder.addCapability(spv::CapabilityGroupNonUniform);
7140 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7141 break;
7142 case glslang::EOpSubgroupAdd:
7143 case glslang::EOpSubgroupMul:
7144 case glslang::EOpSubgroupMin:
7145 case glslang::EOpSubgroupMax:
7146 case glslang::EOpSubgroupAnd:
7147 case glslang::EOpSubgroupOr:
7148 case glslang::EOpSubgroupXor:
7149 case glslang::EOpSubgroupInclusiveAdd:
7150 case glslang::EOpSubgroupInclusiveMul:
7151 case glslang::EOpSubgroupInclusiveMin:
7152 case glslang::EOpSubgroupInclusiveMax:
7153 case glslang::EOpSubgroupInclusiveAnd:
7154 case glslang::EOpSubgroupInclusiveOr:
7155 case glslang::EOpSubgroupInclusiveXor:
7156 case glslang::EOpSubgroupExclusiveAdd:
7157 case glslang::EOpSubgroupExclusiveMul:
7158 case glslang::EOpSubgroupExclusiveMin:
7159 case glslang::EOpSubgroupExclusiveMax:
7160 case glslang::EOpSubgroupExclusiveAnd:
7161 case glslang::EOpSubgroupExclusiveOr:
7162 case glslang::EOpSubgroupExclusiveXor:
7163 builder.addCapability(spv::CapabilityGroupNonUniform);
7164 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7165 break;
7166 case glslang::EOpSubgroupClusteredAdd:
7167 case glslang::EOpSubgroupClusteredMul:
7168 case glslang::EOpSubgroupClusteredMin:
7169 case glslang::EOpSubgroupClusteredMax:
7170 case glslang::EOpSubgroupClusteredAnd:
7171 case glslang::EOpSubgroupClusteredOr:
7172 case glslang::EOpSubgroupClusteredXor:
7173 builder.addCapability(spv::CapabilityGroupNonUniform);
7174 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7175 break;
7176 case glslang::EOpSubgroupQuadBroadcast:
7177 case glslang::EOpSubgroupQuadSwapHorizontal:
7178 case glslang::EOpSubgroupQuadSwapVertical:
7179 case glslang::EOpSubgroupQuadSwapDiagonal:
7180 builder.addCapability(spv::CapabilityGroupNonUniform);
7181 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7182 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007183 case glslang::EOpSubgroupPartitionedAdd:
7184 case glslang::EOpSubgroupPartitionedMul:
7185 case glslang::EOpSubgroupPartitionedMin:
7186 case glslang::EOpSubgroupPartitionedMax:
7187 case glslang::EOpSubgroupPartitionedAnd:
7188 case glslang::EOpSubgroupPartitionedOr:
7189 case glslang::EOpSubgroupPartitionedXor:
7190 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7191 case glslang::EOpSubgroupPartitionedInclusiveMul:
7192 case glslang::EOpSubgroupPartitionedInclusiveMin:
7193 case glslang::EOpSubgroupPartitionedInclusiveMax:
7194 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7195 case glslang::EOpSubgroupPartitionedInclusiveOr:
7196 case glslang::EOpSubgroupPartitionedInclusiveXor:
7197 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7198 case glslang::EOpSubgroupPartitionedExclusiveMul:
7199 case glslang::EOpSubgroupPartitionedExclusiveMin:
7200 case glslang::EOpSubgroupPartitionedExclusiveMax:
7201 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7202 case glslang::EOpSubgroupPartitionedExclusiveOr:
7203 case glslang::EOpSubgroupPartitionedExclusiveXor:
7204 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7205 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7206 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007207 default: assert(0 && "Unhandled subgroup operation!");
7208 }
7209
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007210
7211 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7212 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007213 const bool isBool = typeProxy == glslang::EbtBool;
7214
7215 spv::Op opCode = spv::OpNop;
7216
7217 // Figure out which opcode to use.
7218 switch (op) {
7219 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7220 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7221 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7222 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7223 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7224 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7225 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7226 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7227 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7228 case glslang::EOpSubgroupBallotBitCount:
7229 case glslang::EOpSubgroupBallotInclusiveBitCount:
7230 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7231 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7232 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7233 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7234 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7235 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7236 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7237 case glslang::EOpSubgroupAdd:
7238 case glslang::EOpSubgroupInclusiveAdd:
7239 case glslang::EOpSubgroupExclusiveAdd:
7240 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007241 case glslang::EOpSubgroupPartitionedAdd:
7242 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7243 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007244 if (isFloat) {
7245 opCode = spv::OpGroupNonUniformFAdd;
7246 } else {
7247 opCode = spv::OpGroupNonUniformIAdd;
7248 }
7249 break;
7250 case glslang::EOpSubgroupMul:
7251 case glslang::EOpSubgroupInclusiveMul:
7252 case glslang::EOpSubgroupExclusiveMul:
7253 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007254 case glslang::EOpSubgroupPartitionedMul:
7255 case glslang::EOpSubgroupPartitionedInclusiveMul:
7256 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007257 if (isFloat) {
7258 opCode = spv::OpGroupNonUniformFMul;
7259 } else {
7260 opCode = spv::OpGroupNonUniformIMul;
7261 }
7262 break;
7263 case glslang::EOpSubgroupMin:
7264 case glslang::EOpSubgroupInclusiveMin:
7265 case glslang::EOpSubgroupExclusiveMin:
7266 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007267 case glslang::EOpSubgroupPartitionedMin:
7268 case glslang::EOpSubgroupPartitionedInclusiveMin:
7269 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007270 if (isFloat) {
7271 opCode = spv::OpGroupNonUniformFMin;
7272 } else if (isUnsigned) {
7273 opCode = spv::OpGroupNonUniformUMin;
7274 } else {
7275 opCode = spv::OpGroupNonUniformSMin;
7276 }
7277 break;
7278 case glslang::EOpSubgroupMax:
7279 case glslang::EOpSubgroupInclusiveMax:
7280 case glslang::EOpSubgroupExclusiveMax:
7281 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007282 case glslang::EOpSubgroupPartitionedMax:
7283 case glslang::EOpSubgroupPartitionedInclusiveMax:
7284 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007285 if (isFloat) {
7286 opCode = spv::OpGroupNonUniformFMax;
7287 } else if (isUnsigned) {
7288 opCode = spv::OpGroupNonUniformUMax;
7289 } else {
7290 opCode = spv::OpGroupNonUniformSMax;
7291 }
7292 break;
7293 case glslang::EOpSubgroupAnd:
7294 case glslang::EOpSubgroupInclusiveAnd:
7295 case glslang::EOpSubgroupExclusiveAnd:
7296 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007297 case glslang::EOpSubgroupPartitionedAnd:
7298 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7299 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007300 if (isBool) {
7301 opCode = spv::OpGroupNonUniformLogicalAnd;
7302 } else {
7303 opCode = spv::OpGroupNonUniformBitwiseAnd;
7304 }
7305 break;
7306 case glslang::EOpSubgroupOr:
7307 case glslang::EOpSubgroupInclusiveOr:
7308 case glslang::EOpSubgroupExclusiveOr:
7309 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007310 case glslang::EOpSubgroupPartitionedOr:
7311 case glslang::EOpSubgroupPartitionedInclusiveOr:
7312 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007313 if (isBool) {
7314 opCode = spv::OpGroupNonUniformLogicalOr;
7315 } else {
7316 opCode = spv::OpGroupNonUniformBitwiseOr;
7317 }
7318 break;
7319 case glslang::EOpSubgroupXor:
7320 case glslang::EOpSubgroupInclusiveXor:
7321 case glslang::EOpSubgroupExclusiveXor:
7322 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007323 case glslang::EOpSubgroupPartitionedXor:
7324 case glslang::EOpSubgroupPartitionedInclusiveXor:
7325 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007326 if (isBool) {
7327 opCode = spv::OpGroupNonUniformLogicalXor;
7328 } else {
7329 opCode = spv::OpGroupNonUniformBitwiseXor;
7330 }
7331 break;
7332 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7333 case glslang::EOpSubgroupQuadSwapHorizontal:
7334 case glslang::EOpSubgroupQuadSwapVertical:
7335 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7336 default: assert(0 && "Unhandled subgroup operation!");
7337 }
7338
John Kessenich149afc32018-08-14 13:31:43 -06007339 // get the right Group Operation
7340 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007341 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007342 default:
7343 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007344 case glslang::EOpSubgroupBallotBitCount:
7345 case glslang::EOpSubgroupAdd:
7346 case glslang::EOpSubgroupMul:
7347 case glslang::EOpSubgroupMin:
7348 case glslang::EOpSubgroupMax:
7349 case glslang::EOpSubgroupAnd:
7350 case glslang::EOpSubgroupOr:
7351 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007352 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007353 break;
7354 case glslang::EOpSubgroupBallotInclusiveBitCount:
7355 case glslang::EOpSubgroupInclusiveAdd:
7356 case glslang::EOpSubgroupInclusiveMul:
7357 case glslang::EOpSubgroupInclusiveMin:
7358 case glslang::EOpSubgroupInclusiveMax:
7359 case glslang::EOpSubgroupInclusiveAnd:
7360 case glslang::EOpSubgroupInclusiveOr:
7361 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007362 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007363 break;
7364 case glslang::EOpSubgroupBallotExclusiveBitCount:
7365 case glslang::EOpSubgroupExclusiveAdd:
7366 case glslang::EOpSubgroupExclusiveMul:
7367 case glslang::EOpSubgroupExclusiveMin:
7368 case glslang::EOpSubgroupExclusiveMax:
7369 case glslang::EOpSubgroupExclusiveAnd:
7370 case glslang::EOpSubgroupExclusiveOr:
7371 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007372 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007373 break;
7374 case glslang::EOpSubgroupClusteredAdd:
7375 case glslang::EOpSubgroupClusteredMul:
7376 case glslang::EOpSubgroupClusteredMin:
7377 case glslang::EOpSubgroupClusteredMax:
7378 case glslang::EOpSubgroupClusteredAnd:
7379 case glslang::EOpSubgroupClusteredOr:
7380 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007381 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007382 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007383 case glslang::EOpSubgroupPartitionedAdd:
7384 case glslang::EOpSubgroupPartitionedMul:
7385 case glslang::EOpSubgroupPartitionedMin:
7386 case glslang::EOpSubgroupPartitionedMax:
7387 case glslang::EOpSubgroupPartitionedAnd:
7388 case glslang::EOpSubgroupPartitionedOr:
7389 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007390 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007391 break;
7392 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7393 case glslang::EOpSubgroupPartitionedInclusiveMul:
7394 case glslang::EOpSubgroupPartitionedInclusiveMin:
7395 case glslang::EOpSubgroupPartitionedInclusiveMax:
7396 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7397 case glslang::EOpSubgroupPartitionedInclusiveOr:
7398 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007399 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007400 break;
7401 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7402 case glslang::EOpSubgroupPartitionedExclusiveMul:
7403 case glslang::EOpSubgroupPartitionedExclusiveMin:
7404 case glslang::EOpSubgroupPartitionedExclusiveMax:
7405 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7406 case glslang::EOpSubgroupPartitionedExclusiveOr:
7407 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007408 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007409 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007410 }
7411
John Kessenich149afc32018-08-14 13:31:43 -06007412 // build the instruction
7413 std::vector<spv::IdImmediate> spvGroupOperands;
7414
7415 // Every operation begins with the Execution Scope operand.
7416 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7417 spvGroupOperands.push_back(executionScope);
7418
7419 // Next, for all operations that use a Group Operation, push that as an operand.
7420 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007421 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007422 spvGroupOperands.push_back(groupOperand);
7423 }
7424
John Kessenich66011cb2018-03-06 16:12:04 -07007425 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007426 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7427 spv::IdImmediate operand = { true, *opIt };
7428 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007429 }
7430
7431 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007432 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007433 switch (op) {
7434 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007435 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7436 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7437 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7438 }
7439 if (directionId != spv::NoResult) {
7440 spv::IdImmediate direction = { true, directionId };
7441 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007442 }
7443
7444 return builder.createOp(opCode, typeId, spvGroupOperands);
7445}
7446
John Kessenich8985fc92020-03-03 10:25:07 -07007447spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7448 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007449{
John Kessenich66011cb2018-03-06 16:12:04 -07007450 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7451 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007452
John Kessenich140f3df2015-06-26 16:58:36 -06007453 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007454 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007455 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007456 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007457 spv::Id typeId0 = 0;
7458 if (consumedOperands > 0)
7459 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007460 spv::Id typeId1 = 0;
7461 if (consumedOperands > 1)
7462 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007463 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007464
7465 switch (op) {
7466 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007467 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007468 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007469 else if (isUnsigned)
7470 libCall = spv::GLSLstd450UMin;
7471 else
7472 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007473 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007474 break;
7475 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007476 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007477 break;
7478 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007479 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007480 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007481 else if (isUnsigned)
7482 libCall = spv::GLSLstd450UMax;
7483 else
7484 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007485 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007486 break;
7487 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007488 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007489 break;
7490 case glslang::EOpDot:
7491 opCode = spv::OpDot;
7492 break;
7493 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007494 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007495 break;
7496
7497 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007498 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007499 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007500 else if (isUnsigned)
7501 libCall = spv::GLSLstd450UClamp;
7502 else
7503 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007504 builder.promoteScalar(precision, operands.front(), operands[1]);
7505 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007506 break;
7507 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007508 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7509 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007510 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007511 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007512 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007513 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007514 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007515 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007516 break;
7517 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007518 libCall = spv::GLSLstd450Step;
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::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007522 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007523 builder.promoteScalar(precision, operands[0], operands[2]);
7524 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007525 break;
7526
7527 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007528 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007529 break;
7530 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007531 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007532 break;
7533 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007534 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007535 break;
7536 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007537 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007538 break;
7539 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007540 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007541 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007542 case glslang::EOpBarrier:
7543 {
7544 // This is for the extended controlBarrier function, with four operands.
7545 // The unextended barrier() goes through createNoArgOperation.
7546 assert(operands.size() == 4);
7547 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7548 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7549 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007550 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7551 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007552 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7553 spv::MemorySemanticsMakeVisibleKHRMask |
7554 spv::MemorySemanticsOutputMemoryKHRMask |
7555 spv::MemorySemanticsVolatileMask)) {
7556 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7557 }
John Kessenich8985fc92020-03-03 10:25:07 -07007558 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7559 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007560 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7561 }
7562 return 0;
7563 }
7564 break;
7565 case glslang::EOpMemoryBarrier:
7566 {
7567 // This is for the extended memoryBarrier function, with three operands.
7568 // The unextended memoryBarrier() goes through createNoArgOperation.
7569 assert(operands.size() == 3);
7570 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7571 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7572 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7573 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7574 spv::MemorySemanticsMakeVisibleKHRMask |
7575 spv::MemorySemanticsOutputMemoryKHRMask |
7576 spv::MemorySemanticsVolatileMask)) {
7577 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7578 }
7579 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7580 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7581 }
7582 return 0;
7583 }
7584 break;
7585
John Kessenicha28f7a72019-08-06 07:00:58 -06007586#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007587 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007588 if (typeProxy == glslang::EbtFloat16)
7589 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007590 libCall = spv::GLSLstd450InterpolateAtSample;
7591 break;
7592 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007593 if (typeProxy == glslang::EbtFloat16)
7594 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007595 libCall = spv::GLSLstd450InterpolateAtOffset;
7596 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007597 case glslang::EOpAddCarry:
7598 opCode = spv::OpIAddCarry;
7599 typeId = builder.makeStructResultType(typeId0, typeId0);
7600 consumedOperands = 2;
7601 break;
7602 case glslang::EOpSubBorrow:
7603 opCode = spv::OpISubBorrow;
7604 typeId = builder.makeStructResultType(typeId0, typeId0);
7605 consumedOperands = 2;
7606 break;
7607 case glslang::EOpUMulExtended:
7608 opCode = spv::OpUMulExtended;
7609 typeId = builder.makeStructResultType(typeId0, typeId0);
7610 consumedOperands = 2;
7611 break;
7612 case glslang::EOpIMulExtended:
7613 opCode = spv::OpSMulExtended;
7614 typeId = builder.makeStructResultType(typeId0, typeId0);
7615 consumedOperands = 2;
7616 break;
7617 case glslang::EOpBitfieldExtract:
7618 if (isUnsigned)
7619 opCode = spv::OpBitFieldUExtract;
7620 else
7621 opCode = spv::OpBitFieldSExtract;
7622 break;
7623 case glslang::EOpBitfieldInsert:
7624 opCode = spv::OpBitFieldInsert;
7625 break;
7626
7627 case glslang::EOpFma:
7628 libCall = spv::GLSLstd450Fma;
7629 break;
7630 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007631 {
7632 libCall = spv::GLSLstd450FrexpStruct;
7633 assert(builder.isPointerType(typeId1));
7634 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007635 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007636 if (width == 16)
7637 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7638 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007639 if (builder.getNumComponents(operands[0]) == 1)
7640 frexpIntType = builder.makeIntegerType(width, true);
7641 else
John Kessenich8985fc92020-03-03 10:25:07 -07007642 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7643 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007644 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7645 consumedOperands = 1;
7646 }
John Kessenich55e7d112015-11-15 21:33:39 -07007647 break;
7648 case glslang::EOpLdexp:
7649 libCall = spv::GLSLstd450Ldexp;
7650 break;
7651
Rex Xu574ab042016-04-14 16:53:07 +08007652 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007653 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007654
John Kessenich66011cb2018-03-06 16:12:04 -07007655 case glslang::EOpSubgroupBroadcast:
7656 case glslang::EOpSubgroupBallotBitExtract:
7657 case glslang::EOpSubgroupShuffle:
7658 case glslang::EOpSubgroupShuffleXor:
7659 case glslang::EOpSubgroupShuffleUp:
7660 case glslang::EOpSubgroupShuffleDown:
7661 case glslang::EOpSubgroupClusteredAdd:
7662 case glslang::EOpSubgroupClusteredMul:
7663 case glslang::EOpSubgroupClusteredMin:
7664 case glslang::EOpSubgroupClusteredMax:
7665 case glslang::EOpSubgroupClusteredAnd:
7666 case glslang::EOpSubgroupClusteredOr:
7667 case glslang::EOpSubgroupClusteredXor:
7668 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007669 case glslang::EOpSubgroupPartitionedAdd:
7670 case glslang::EOpSubgroupPartitionedMul:
7671 case glslang::EOpSubgroupPartitionedMin:
7672 case glslang::EOpSubgroupPartitionedMax:
7673 case glslang::EOpSubgroupPartitionedAnd:
7674 case glslang::EOpSubgroupPartitionedOr:
7675 case glslang::EOpSubgroupPartitionedXor:
7676 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7677 case glslang::EOpSubgroupPartitionedInclusiveMul:
7678 case glslang::EOpSubgroupPartitionedInclusiveMin:
7679 case glslang::EOpSubgroupPartitionedInclusiveMax:
7680 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7681 case glslang::EOpSubgroupPartitionedInclusiveOr:
7682 case glslang::EOpSubgroupPartitionedInclusiveXor:
7683 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7684 case glslang::EOpSubgroupPartitionedExclusiveMul:
7685 case glslang::EOpSubgroupPartitionedExclusiveMin:
7686 case glslang::EOpSubgroupPartitionedExclusiveMax:
7687 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7688 case glslang::EOpSubgroupPartitionedExclusiveOr:
7689 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007690 return createSubgroupOperation(op, typeId, operands, typeProxy);
7691
Rex Xu9d93a232016-05-05 12:30:44 +08007692 case glslang::EOpSwizzleInvocations:
7693 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7694 libCall = spv::SwizzleInvocationsAMD;
7695 break;
7696 case glslang::EOpSwizzleInvocationsMasked:
7697 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7698 libCall = spv::SwizzleInvocationsMaskedAMD;
7699 break;
7700 case glslang::EOpWriteInvocation:
7701 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7702 libCall = spv::WriteInvocationAMD;
7703 break;
7704
7705 case glslang::EOpMin3:
7706 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7707 if (isFloat)
7708 libCall = spv::FMin3AMD;
7709 else {
7710 if (isUnsigned)
7711 libCall = spv::UMin3AMD;
7712 else
7713 libCall = spv::SMin3AMD;
7714 }
7715 break;
7716 case glslang::EOpMax3:
7717 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7718 if (isFloat)
7719 libCall = spv::FMax3AMD;
7720 else {
7721 if (isUnsigned)
7722 libCall = spv::UMax3AMD;
7723 else
7724 libCall = spv::SMax3AMD;
7725 }
7726 break;
7727 case glslang::EOpMid3:
7728 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7729 if (isFloat)
7730 libCall = spv::FMid3AMD;
7731 else {
7732 if (isUnsigned)
7733 libCall = spv::UMid3AMD;
7734 else
7735 libCall = spv::SMid3AMD;
7736 }
7737 break;
7738
7739 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007740 if (typeProxy == glslang::EbtFloat16)
7741 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007742 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7743 libCall = spv::InterpolateAtVertexAMD;
7744 break;
Chao Chen3c366992018-09-19 11:41:59 -07007745
Daniel Kochdb32b242020-03-17 20:42:47 -04007746 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007747 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007748 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007749 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007750 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007751 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007752 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007753 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007754 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007755 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007756
7757 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007758 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7759 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007760 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007761 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7762 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007763 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007764 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7765 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007766 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007767 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7768 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007769 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007770 typeId = builder.makeBoolType();
7771 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007772 break;
7773 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007774 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007775 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007776 break;
7777 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007778 typeId = builder.makeFloatType(32);
7779 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007780 break;
7781 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007782 typeId = builder.makeIntType(32);
7783 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007784 break;
7785 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007786 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007787 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007788 break;
7789 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007790 typeId = builder.makeIntType(32);
7791 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007792 break;
7793 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007794 typeId = builder.makeIntType(32);
7795 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007796 break;
7797 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007798 typeId = builder.makeIntType(32);
7799 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007800 break;
7801 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007802 typeId = builder.makeIntType(32);
7803 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007804 break;
7805 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007806 typeId = builder.makeIntType(32);
7807 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007808 break;
7809 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007810 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7811 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007812 break;
7813 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007814 typeId = builder.makeBoolType();
7815 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007816 break;
7817 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007818 typeId = builder.makeBoolType();
7819 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007820 break;
7821 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007822 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7823 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007824 break;
7825 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007826 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7827 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007828 break;
7829 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007830 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7831 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007832 break;
7833 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007834 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7835 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007836 break;
7837 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007838 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007839 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007840 break;
7841 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007842 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007843 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007844 break;
Chao Chen3c366992018-09-19 11:41:59 -07007845 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7846 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7847 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007848 case glslang::EOpCooperativeMatrixMulAdd:
7849 opCode = spv::OpCooperativeMatrixMulAddNV;
7850 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007851#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007852 default:
7853 return 0;
7854 }
7855
7856 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007857 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007858 // Use an extended instruction from the standard library.
7859 // Construct the call arguments, without modifying the original operands vector.
7860 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7861 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007862 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007863 } else if (opCode == spv::OpDot && !isFloat) {
7864 // int dot(int, int)
7865 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7866 const int componentCount = builder.getNumComponents(operands[0]);
7867 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7868 builder.setPrecision(mulOp, precision);
7869 id = builder.createCompositeExtract(mulOp, typeId, 0);
7870 for (int i = 1; i < componentCount; ++i) {
7871 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007872 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007873 }
John Kessenich2359bd02015-12-06 19:29:11 -07007874 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007875 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007876 case 0:
7877 // should all be handled by visitAggregate and createNoArgOperation
7878 assert(0);
7879 return 0;
7880 case 1:
7881 // should all be handled by createUnaryOperation
7882 assert(0);
7883 return 0;
7884 case 2:
7885 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7886 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007887 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007888 // anything 3 or over doesn't have l-value operands, so all should be consumed
7889 assert(consumedOperands == operands.size());
7890 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007891 break;
7892 }
7893 }
7894
John Kessenichb9197c82019-08-11 07:41:45 -06007895#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007896 // Decode the return types that were structures
7897 switch (op) {
7898 case glslang::EOpAddCarry:
7899 case glslang::EOpSubBorrow:
7900 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7901 id = builder.createCompositeExtract(id, typeId0, 0);
7902 break;
7903 case glslang::EOpUMulExtended:
7904 case glslang::EOpIMulExtended:
7905 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7906 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7907 break;
7908 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007909 {
7910 assert(operands.size() == 2);
7911 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7912 // "exp" is floating-point type (from HLSL intrinsic)
7913 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7914 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7915 builder.createStore(member1, operands[1]);
7916 } else
7917 // "exp" is integer type (from GLSL built-in function)
7918 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7919 id = builder.createCompositeExtract(id, typeId0, 0);
7920 }
John Kessenich55e7d112015-11-15 21:33:39 -07007921 break;
7922 default:
7923 break;
7924 }
John Kessenichb9197c82019-08-11 07:41:45 -06007925#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007926
John Kessenich32cfd492016-02-02 12:37:46 -07007927 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007928}
7929
Rex Xu9d93a232016-05-05 12:30:44 +08007930// Intrinsics with no arguments (or no return value, and no precision).
7931spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007932{
Jeff Bolz36831c92018-09-05 10:11:41 -05007933 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007934 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7935 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007936
7937 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007938 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007939 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007940 if (glslangIntermediate->usingVulkanMemoryModel()) {
7941 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7942 spv::MemorySemanticsOutputMemoryKHRMask |
7943 spv::MemorySemanticsAcquireReleaseMask);
7944 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7945 } else {
7946 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7947 }
John Kessenich82979362017-12-11 04:02:24 -07007948 } else {
7949 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7950 spv::MemorySemanticsWorkgroupMemoryMask |
7951 spv::MemorySemanticsAcquireReleaseMask);
7952 }
John Kessenich140f3df2015-06-26 16:58:36 -06007953 return 0;
7954 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007955 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7956 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007957 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007958 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007959 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7960 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007961 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007962 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007963 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7964 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007965 return 0;
7966 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007967 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7968 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007969 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007970#ifndef GLSLANG_WEB
7971 case glslang::EOpMemoryBarrierAtomicCounter:
7972 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7973 spv::MemorySemanticsAcquireReleaseMask);
7974 return 0;
7975 case glslang::EOpMemoryBarrierImage:
7976 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7977 spv::MemorySemanticsAcquireReleaseMask);
7978 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007979 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007980 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007981 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007982 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007983 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007984 case glslang::EOpDeviceMemoryBarrier:
7985 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7986 spv::MemorySemanticsImageMemoryMask |
7987 spv::MemorySemanticsAcquireReleaseMask);
7988 return 0;
7989 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7990 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7991 spv::MemorySemanticsImageMemoryMask |
7992 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007993 return 0;
7994 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007995 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7996 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007997 return 0;
7998 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007999 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8000 spv::MemorySemanticsWorkgroupMemoryMask |
8001 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008002 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008003 case glslang::EOpSubgroupBarrier:
8004 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8005 spv::MemorySemanticsAcquireReleaseMask);
8006 return spv::NoResult;
8007 case glslang::EOpSubgroupMemoryBarrier:
8008 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8009 spv::MemorySemanticsAcquireReleaseMask);
8010 return spv::NoResult;
8011 case glslang::EOpSubgroupMemoryBarrierBuffer:
8012 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8013 spv::MemorySemanticsAcquireReleaseMask);
8014 return spv::NoResult;
8015 case glslang::EOpSubgroupMemoryBarrierImage:
8016 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8017 spv::MemorySemanticsAcquireReleaseMask);
8018 return spv::NoResult;
8019 case glslang::EOpSubgroupMemoryBarrierShared:
8020 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8021 spv::MemorySemanticsAcquireReleaseMask);
8022 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008023
8024 case glslang::EOpEmitVertex:
8025 builder.createNoResultOp(spv::OpEmitVertex);
8026 return 0;
8027 case glslang::EOpEndPrimitive:
8028 builder.createNoResultOp(spv::OpEndPrimitive);
8029 return 0;
8030
John Kessenich66011cb2018-03-06 16:12:04 -07008031 case glslang::EOpSubgroupElect: {
8032 std::vector<spv::Id> operands;
8033 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8034 }
Rex Xu9d93a232016-05-05 12:30:44 +08008035 case glslang::EOpTime:
8036 {
8037 std::vector<spv::Id> args; // Dummy arguments
8038 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8039 return builder.setPrecision(id, precision);
8040 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008041 case glslang::EOpIgnoreIntersection:
8042 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008043 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008044 case glslang::EOpTerminateRay:
8045 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008046 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008047 case glslang::EOpRayQueryInitialize:
8048 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8049 return 0;
8050 case glslang::EOpRayQueryTerminate:
8051 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8052 return 0;
8053 case glslang::EOpRayQueryGenerateIntersection:
8054 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8055 return 0;
8056 case glslang::EOpRayQueryConfirmIntersection:
8057 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8058 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008059 case glslang::EOpBeginInvocationInterlock:
8060 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8061 return 0;
8062 case glslang::EOpEndInvocationInterlock:
8063 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8064 return 0;
8065
Jeff Bolzba6170b2019-07-01 09:23:23 -05008066 case glslang::EOpIsHelperInvocation:
8067 {
8068 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008069 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8070 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8071 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008072 }
8073
amhagan91fb0092019-07-10 21:14:38 -04008074 case glslang::EOpReadClockSubgroupKHR: {
8075 std::vector<spv::Id> args;
8076 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8077 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8078 builder.addCapability(spv::CapabilityShaderClockKHR);
8079 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8080 }
8081
8082 case glslang::EOpReadClockDeviceKHR: {
8083 std::vector<spv::Id> args;
8084 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8085 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8086 builder.addCapability(spv::CapabilityShaderClockKHR);
8087 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8088 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008089#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008090 default:
John Kessenich155d3512019-08-08 23:29:20 -06008091 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008092 }
John Kessenich155d3512019-08-08 23:29:20 -06008093
8094 logger->missingFunctionality("unknown operation with no arguments");
8095
8096 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008097}
8098
8099spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8100{
John Kessenich2f273362015-07-18 22:34:27 -06008101 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008102 spv::Id id;
8103 if (symbolValues.end() != iter) {
8104 id = iter->second;
8105 return id;
8106 }
8107
8108 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008109 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008110 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008111 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008112 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008113 if (forcedType.second != spv::NoType)
8114 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008115
Rex Xuc884b4a2016-06-29 15:03:44 +08008116 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008117 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8118 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8119 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008120#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008121 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008122 if (symbol->getQualifier().hasComponent())
8123 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8124 if (symbol->getQualifier().hasIndex())
8125 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008126#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008127 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008128 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008129 // atomic counters use this:
8130 if (symbol->getQualifier().hasOffset())
8131 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008132 }
8133
scygan2c864272016-05-18 18:09:17 +02008134 if (symbol->getQualifier().hasLocation())
8135 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008136 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008137 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008138 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008139 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008140 }
John Kessenich140f3df2015-06-26 16:58:36 -06008141 if (symbol->getQualifier().hasSet())
8142 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008143 else if (IsDescriptorResource(symbol->getType())) {
8144 // default to 0
8145 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8146 }
John Kessenich140f3df2015-06-26 16:58:36 -06008147 if (symbol->getQualifier().hasBinding())
8148 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008149 else if (IsDescriptorResource(symbol->getType())) {
8150 // default to 0
8151 builder.addDecoration(id, spv::DecorationBinding, 0);
8152 }
John Kessenich6c292d32016-02-15 20:58:50 -07008153 if (symbol->getQualifier().hasAttachment())
8154 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008155 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008156 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008157 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008158 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008159 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8160 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8161 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8162 }
8163 if (symbol->getQualifier().hasXfbOffset())
8164 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008165 }
8166
John Kessenichb9197c82019-08-11 07:41:45 -06008167 // add built-in variable decoration
8168 if (builtIn != spv::BuiltInMax) {
8169 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8170 }
8171
8172#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008173 if (symbol->getType().isImage()) {
8174 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008175 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8176 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008177 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008178 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008179 }
8180
John Kessenich5611c6d2018-04-05 11:25:02 -06008181 // nonuniform
8182 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8183
chaoc0ad6a4e2016-12-19 16:29:34 -08008184 if (builtIn == spv::BuiltInSampleMask) {
8185 spv::Decoration decoration;
8186 // GL_NV_sample_mask_override_coverage extension
8187 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008188 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008189 else
8190 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008191 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008192 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008193 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008194 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8195 }
8196 }
chaoc771d89f2017-01-13 01:10:53 -08008197 else if (builtIn == spv::BuiltInLayer) {
8198 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008199 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008200 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008201 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8202 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8203 }
John Kessenichb41bff62017-08-11 13:07:17 -06008204 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008205 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8206 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008207 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8208 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8209 }
8210 }
8211
chaoc6e5acae2016-12-20 13:28:52 -08008212 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008213 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008214 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008215 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8216 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008217 if (symbol->getQualifier().pervertexNV) {
8218 builder.addDecoration(id, spv::DecorationPerVertexNV);
8219 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8220 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8221 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008222
John Kessenich5d610ee2018-03-07 18:05:55 -07008223 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8224 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8225 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8226 symbol->getType().getQualifier().semanticName);
8227 }
8228
John Kessenich7015bd62019-08-01 03:28:08 -06008229 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008230 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8231 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008232 }
John Kessenichb9197c82019-08-11 07:41:45 -06008233#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008234
John Kessenich140f3df2015-06-26 16:58:36 -06008235 return id;
8236}
8237
John Kessenicha28f7a72019-08-06 07:00:58 -06008238#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008239// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8240void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8241{
8242 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008243 if (qualifier.perPrimitiveNV) {
8244 // Need to add capability/extension for fragment shader.
8245 // Mesh shader already adds this by default.
8246 if (glslangIntermediate->getStage() == EShLangFragment) {
8247 builder.addCapability(spv::CapabilityMeshShadingNV);
8248 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8249 }
Chao Chen3c366992018-09-19 11:41:59 -07008250 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008251 }
Chao Chen3c366992018-09-19 11:41:59 -07008252 if (qualifier.perViewNV)
8253 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8254 if (qualifier.perTaskNV)
8255 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8256 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008257 if (qualifier.perPrimitiveNV) {
8258 // Need to add capability/extension for fragment shader.
8259 // Mesh shader already adds this by default.
8260 if (glslangIntermediate->getStage() == EShLangFragment) {
8261 builder.addCapability(spv::CapabilityMeshShadingNV);
8262 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8263 }
Chao Chen3c366992018-09-19 11:41:59 -07008264 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008265 }
Chao Chen3c366992018-09-19 11:41:59 -07008266 if (qualifier.perViewNV)
8267 builder.addDecoration(id, spv::DecorationPerViewNV);
8268 if (qualifier.perTaskNV)
8269 builder.addDecoration(id, spv::DecorationPerTaskNV);
8270 }
8271}
8272#endif
8273
John Kessenich55e7d112015-11-15 21:33:39 -07008274// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008275// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008276//
8277// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8278//
8279// Recursively walk the nodes. The nodes form a tree whose leaves are
8280// regular constants, which themselves are trees that createSpvConstant()
8281// recursively walks. So, this function walks the "top" of the tree:
8282// - emit specialization constant-building instructions for specConstant
8283// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008284spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008285{
John Kessenich7cc0e282016-03-20 00:46:02 -06008286 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008287
qining4f4bb812016-04-03 23:55:17 -04008288 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008289 if (! node.getQualifier().specConstant) {
8290 // hand off to the non-spec-constant path
8291 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8292 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008293 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8294 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8295 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008296 }
8297
8298 // We now know we have a specialization constant to build
8299
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008300 // Extra capabilities may be needed.
8301 if (node.getType().contains8BitInt())
8302 builder.addCapability(spv::CapabilityInt8);
8303 if (node.getType().contains16BitFloat())
8304 builder.addCapability(spv::CapabilityFloat16);
8305 if (node.getType().contains16BitInt())
8306 builder.addCapability(spv::CapabilityInt16);
8307 if (node.getType().contains64BitInt())
8308 builder.addCapability(spv::CapabilityInt64);
8309 if (node.getType().containsDouble())
8310 builder.addCapability(spv::CapabilityFloat64);
8311
John Kessenichd94c0032016-05-30 19:29:40 -06008312 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008313 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8314 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8315 std::vector<spv::Id> dimConstId;
8316 for (int dim = 0; dim < 3; ++dim) {
8317 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8318 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008319 if (specConst) {
8320 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8321 glslangIntermediate->getLocalSizeSpecId(dim));
8322 }
qining4f4bb812016-04-03 23:55:17 -04008323 }
8324 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8325 }
8326
8327 // An AST node labelled as specialization constant should be a symbol node.
8328 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8329 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008330 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008331 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008332 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8333 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8334 // will set the builder into spec constant op instruction generating mode.
8335 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008336 result = accessChainLoad(sub_tree->getType());
8337 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008338 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008339 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008340 } else {
8341 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008342 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008343 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008344 builder.addName(result, sn->getName().c_str());
8345 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008346 }
qining4f4bb812016-04-03 23:55:17 -04008347
8348 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8349 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008350 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008351 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008352}
8353
John Kessenich140f3df2015-06-26 16:58:36 -06008354// Use 'consts' as the flattened glslang source of scalar constants to recursively
8355// build the aggregate SPIR-V constant.
8356//
8357// If there are not enough elements present in 'consts', 0 will be substituted;
8358// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8359//
John Kessenich8985fc92020-03-03 10:25:07 -07008360spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8361 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008362{
8363 // vector of constants for SPIR-V
8364 std::vector<spv::Id> spvConsts;
8365
8366 // Type is used for struct and array constants
8367 spv::Id typeId = convertGlslangToSpvType(glslangType);
8368
8369 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008370 glslang::TType elementType(glslangType, 0);
8371 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008372 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008373 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008374 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008375 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008376 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008377 } else if (glslangType.isCoopMat()) {
8378 glslang::TType componentType(glslangType.getBasicType());
8379 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008380 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008381 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8382 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008383 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008384 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008385 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8386 bool zero = nextConst >= consts.size();
8387 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008388 case glslang::EbtInt:
8389 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8390 break;
8391 case glslang::EbtUint:
8392 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8393 break;
8394 case glslang::EbtFloat:
8395 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8396 break;
8397 case glslang::EbtBool:
8398 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8399 break;
8400#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008401 case glslang::EbtInt8:
8402 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8403 break;
8404 case glslang::EbtUint8:
8405 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8406 break;
8407 case glslang::EbtInt16:
8408 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8409 break;
8410 case glslang::EbtUint16:
8411 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8412 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008413 case glslang::EbtInt64:
8414 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8415 break;
8416 case glslang::EbtUint64:
8417 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8418 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008419 case glslang::EbtDouble:
8420 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8421 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008422 case glslang::EbtFloat16:
8423 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8424 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008425#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008426 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008427 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008428 break;
8429 }
8430 ++nextConst;
8431 }
8432 } else {
8433 // we have a non-aggregate (scalar) constant
8434 bool zero = nextConst >= consts.size();
8435 spv::Id scalar = 0;
8436 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008437 case glslang::EbtInt:
8438 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8439 break;
8440 case glslang::EbtUint:
8441 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8442 break;
8443 case glslang::EbtFloat:
8444 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8445 break;
8446 case glslang::EbtBool:
8447 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8448 break;
8449#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008450 case glslang::EbtInt8:
8451 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8452 break;
8453 case glslang::EbtUint8:
8454 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8455 break;
8456 case glslang::EbtInt16:
8457 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8458 break;
8459 case glslang::EbtUint16:
8460 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8461 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008462 case glslang::EbtInt64:
8463 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8464 break;
8465 case glslang::EbtUint64:
8466 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8467 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008468 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008469 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008470 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008471 case glslang::EbtFloat16:
8472 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8473 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008474 case glslang::EbtReference:
8475 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8476 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8477 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008478#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008479 case glslang::EbtString:
8480 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8481 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008482 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008483 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008484 break;
8485 }
8486 ++nextConst;
8487 return scalar;
8488 }
8489
8490 return builder.makeCompositeConstant(typeId, spvConsts);
8491}
8492
John Kessenich7c1aa102015-10-15 13:29:11 -06008493// Return true if the node is a constant or symbol whose reading has no
8494// non-trivial observable cost or effect.
8495bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8496{
8497 // don't know what this is
8498 if (node == nullptr)
8499 return false;
8500
8501 // a constant is safe
8502 if (node->getAsConstantUnion() != nullptr)
8503 return true;
8504
8505 // not a symbol means non-trivial
8506 if (node->getAsSymbolNode() == nullptr)
8507 return false;
8508
8509 // a symbol, depends on what's being read
8510 switch (node->getType().getQualifier().storage) {
8511 case glslang::EvqTemporary:
8512 case glslang::EvqGlobal:
8513 case glslang::EvqIn:
8514 case glslang::EvqInOut:
8515 case glslang::EvqConst:
8516 case glslang::EvqConstReadOnly:
8517 case glslang::EvqUniform:
8518 return true;
8519 default:
8520 return false;
8521 }
qining25262b32016-05-06 17:25:16 -04008522}
John Kessenich7c1aa102015-10-15 13:29:11 -06008523
8524// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008525// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008526// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008527// Return true if trivial.
8528bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8529{
8530 if (node == nullptr)
8531 return false;
8532
John Kessenich84cc15f2017-05-24 16:44:47 -06008533 // count non scalars as trivial, as well as anything coming from HLSL
8534 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008535 return true;
8536
John Kessenich7c1aa102015-10-15 13:29:11 -06008537 // symbols and constants are trivial
8538 if (isTrivialLeaf(node))
8539 return true;
8540
8541 // otherwise, it needs to be a simple operation or one or two leaf nodes
8542
8543 // not a simple operation
8544 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8545 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8546 if (binaryNode == nullptr && unaryNode == nullptr)
8547 return false;
8548
8549 // not on leaf nodes
8550 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8551 return false;
8552
8553 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8554 return false;
8555 }
8556
8557 switch (node->getAsOperator()->getOp()) {
8558 case glslang::EOpLogicalNot:
8559 case glslang::EOpConvIntToBool:
8560 case glslang::EOpConvUintToBool:
8561 case glslang::EOpConvFloatToBool:
8562 case glslang::EOpConvDoubleToBool:
8563 case glslang::EOpEqual:
8564 case glslang::EOpNotEqual:
8565 case glslang::EOpLessThan:
8566 case glslang::EOpGreaterThan:
8567 case glslang::EOpLessThanEqual:
8568 case glslang::EOpGreaterThanEqual:
8569 case glslang::EOpIndexDirect:
8570 case glslang::EOpIndexDirectStruct:
8571 case glslang::EOpLogicalXor:
8572 case glslang::EOpAny:
8573 case glslang::EOpAll:
8574 return true;
8575 default:
8576 return false;
8577 }
8578}
8579
8580// Emit short-circuiting code, where 'right' is never evaluated unless
8581// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008582spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8583 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008584{
8585 spv::Id boolTypeId = builder.makeBoolType();
8586
8587 // emit left operand
8588 builder.clearAccessChain();
8589 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008590 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008591
8592 // Operands to accumulate OpPhi operands
8593 std::vector<spv::Id> phiOperands;
8594 // accumulate left operand's phi information
8595 phiOperands.push_back(leftId);
8596 phiOperands.push_back(builder.getBuildPoint()->getId());
8597
8598 // Make the two kinds of operation symmetric with a "!"
8599 // || => emit "if (! left) result = right"
8600 // && => emit "if ( left) result = right"
8601 //
8602 // TODO: this runtime "not" for || could be avoided by adding functionality
8603 // to 'builder' to have an "else" without an "then"
8604 if (op == glslang::EOpLogicalOr)
8605 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8606
8607 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008608 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008609
8610 // emit right operand as the "then" part of the "if"
8611 builder.clearAccessChain();
8612 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008613 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008614
8615 // accumulate left operand's phi information
8616 phiOperands.push_back(rightId);
8617 phiOperands.push_back(builder.getBuildPoint()->getId());
8618
8619 // finish the "if"
8620 ifBuilder.makeEndIf();
8621
8622 // phi together the two results
8623 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8624}
8625
John Kessenicha28f7a72019-08-06 07:00:58 -06008626#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008627// Return type Id of the imported set of extended instructions corresponds to the name.
8628// Import this set if it has not been imported yet.
8629spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8630{
8631 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8632 return extBuiltinMap[name];
8633 else {
Rex Xu51596642016-09-21 18:56:12 +08008634 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008635 spv::Id extBuiltins = builder.import(name);
8636 extBuiltinMap[name] = extBuiltins;
8637 return extBuiltins;
8638 }
8639}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008640#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008641
John Kessenich140f3df2015-06-26 16:58:36 -06008642}; // end anonymous namespace
8643
8644namespace glslang {
8645
John Kessenich68d78fd2015-07-12 19:28:10 -06008646void GetSpirvVersion(std::string& version)
8647{
John Kessenich9e55f632015-07-15 10:03:39 -06008648 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008649 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008650 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008651 version = buf;
8652}
8653
John Kessenicha372a3e2017-11-02 22:32:14 -06008654// For low-order part of the generator's magic number. Bump up
8655// when there is a change in the style (e.g., if SSA form changes,
8656// or a different instruction sequence to do something gets used).
8657int GetSpirvGeneratorVersion()
8658{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008659 // return 1; // start
8660 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008661 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008662 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008663 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008664 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8665 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008666 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008667 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008668 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8669 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008670}
8671
John Kessenich140f3df2015-06-26 16:58:36 -06008672// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008673void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008674{
8675 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008676 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008677 if (out.fail())
8678 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008679 for (int i = 0; i < (int)spirv.size(); ++i) {
8680 unsigned int word = spirv[i];
8681 out.write((const char*)&word, 4);
8682 }
8683 out.close();
8684}
8685
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008686// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008687void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008688{
John Kessenich155d3512019-08-08 23:29:20 -06008689#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008690 std::ofstream out;
8691 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008692 if (out.fail())
8693 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008694 out << "\t// " <<
8695 GetSpirvGeneratorVersion() <<
8696 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8697 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008698 if (varName != nullptr) {
8699 out << "\t #pragma once" << std::endl;
8700 out << "const uint32_t " << varName << "[] = {" << std::endl;
8701 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008702 const int WORDS_PER_LINE = 8;
8703 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8704 out << "\t";
8705 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8706 const unsigned int word = spirv[i + j];
8707 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8708 if (i + j + 1 < (int)spirv.size()) {
8709 out << ",";
8710 }
8711 }
8712 out << std::endl;
8713 }
Flavio15017db2017-02-15 14:29:33 -08008714 if (varName != nullptr) {
8715 out << "};";
8716 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008717 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008718#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008719}
8720
John Kessenich140f3df2015-06-26 16:58:36 -06008721//
8722// Set up the glslang traversal
8723//
John Kessenich4e11b612018-08-30 16:56:59 -06008724void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008725{
Lei Zhang17535f72016-05-04 15:55:59 -04008726 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008727 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008728}
8729
John Kessenich4e11b612018-08-30 16:56:59 -06008730void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008731 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008732{
John Kessenich140f3df2015-06-26 16:58:36 -06008733 TIntermNode* root = intermediate.getTreeRoot();
8734
8735 if (root == 0)
8736 return;
8737
John Kessenich4e11b612018-08-30 16:56:59 -06008738 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008739 if (options == nullptr)
8740 options = &defaultOptions;
8741
John Kessenich4e11b612018-08-30 16:56:59 -06008742 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008743
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008744 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008745 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008746 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008747 it.dumpSpv(spirv);
8748
GregFfb03a552018-03-29 11:49:14 -06008749#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008750 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8751 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008752 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008753 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8754 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008755 prelegalization = false;
8756 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008757 else if (options->stripDebugInfo) {
8758 // Strip debug info even if optimization is disabled.
8759 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8760 }
John Kessenich717c80a2018-08-23 15:17:10 -06008761
John Kessenich4e11b612018-08-30 16:56:59 -06008762 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008763 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008764
John Kessenich717c80a2018-08-23 15:17:10 -06008765 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008766 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008767
GregFcd1f1692017-09-21 18:40:22 -06008768#endif
8769
John Kessenich4e11b612018-08-30 16:56:59 -06008770 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008771}
8772
8773}; // end namespace glslang