blob: 9409dcc25e197c025e74140e874c37ae067901b8 [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.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080050 #include "GLSL.ext.NV.h"
Jeff Bolz04d73732019-05-31 13:06:01 -050051 #include "NonSemanticDebugPrintf.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052}
John Kessenich140f3df2015-06-26 16:58:36 -060053
54// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020055#include "../glslang/MachineIndependent/localintermediate.h"
56#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060057#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050058#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060059
John Kessenich140f3df2015-06-26 16:58:36 -060060#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050061#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040062#include <list>
63#include <map>
64#include <stack>
65#include <string>
66#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060067
68namespace {
69
qining4c912612016-04-01 10:35:16 -040070namespace {
71class SpecConstantOpModeGuard {
72public:
73 SpecConstantOpModeGuard(spv::Builder* builder)
74 : builder_(builder) {
75 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040076 }
77 ~SpecConstantOpModeGuard() {
78 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
79 : builder_->setToNormalCodeGenMode();
80 }
qining40887662016-04-03 22:20:42 -040081 void turnOnSpecConstantOpMode() {
82 builder_->setToSpecConstCodeGenMode();
83 }
qining4c912612016-04-01 10:35:16 -040084
85private:
86 spv::Builder* builder_;
87 bool previous_flag_;
88};
John Kessenichead86222018-03-28 18:01:20 -060089
90struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060091 public:
92 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
93 precision(precision)
94#ifndef GLSLANG_WEB
95 ,
96 noContraction(noContraction),
97 nonUniform(nonUniform)
98#endif
99 { }
100
John Kessenichead86222018-03-28 18:01:20 -0600101 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600102
103#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400104 void addNoContraction(spv::Builder&, spv::Id) const { }
105 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600106#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400107 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
108 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600109 protected:
110 spv::Decoration noContraction;
111 spv::Decoration nonUniform;
112#endif
113
John Kessenichead86222018-03-28 18:01:20 -0600114};
115
116} // namespace
qining4c912612016-04-01 10:35:16 -0400117
John Kessenich140f3df2015-06-26 16:58:36 -0600118//
119// The main holder of information for translating glslang to SPIR-V.
120//
121// Derives from the AST walking base class.
122//
123class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
124public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700125 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
126 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700127 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600128
129 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
130 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
131 void visitConstantUnion(glslang::TIntermConstantUnion*);
132 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
133 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
134 void visitSymbol(glslang::TIntermSymbol* symbol);
135 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
136 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
137 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
138
John Kessenichfca82622016-11-26 13:23:20 -0700139 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700140 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600141
142protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700143 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
144 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
145
Rex Xu17ff3432016-10-14 17:41:45 +0800146 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800147 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600148 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500149 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
150 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
151 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
152 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100153 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700154 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700155 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
156 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700157 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600158 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600159 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600160 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600161 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600162 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
163 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
164 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600165 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600166 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600167 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600168 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600169 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
170 glslang::TLayoutPacking, const glslang::TQualifier&);
171 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
172 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700173 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700174 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800175 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600176 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700177 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700178 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
179 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700180 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
181 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100182 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600183
John Kessenich6fccb3c2016-09-19 16:01:41 -0600184 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600185 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600186 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 void makeFunctions(const glslang::TIntermSequence&);
188 void makeGlobalInitializers(const glslang::TIntermSequence&);
189 void visitFunctions(const glslang::TIntermSequence&);
190 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700191 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
192 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600193 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
194 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600195 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
196
John Kessenichead86222018-03-28 18:01:20 -0600197 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
198 glslang::TBasicType typeProxy, bool reduceComparison = true);
199 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
200 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700201 glslang::TBasicType typeProxy,
202 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600203 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
204 glslang::TBasicType typeProxy);
205 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
206 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600207 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600208 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700209 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
210 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
211 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
212 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
213 glslang::TBasicType typeProxy);
214 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
215 spv::Id typeId, std::vector<spv::Id>& operands);
216 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
217 glslang::TBasicType typeProxy);
218 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
219 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800220 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600221 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700222 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400223 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700224 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
225 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600226 bool isTrivialLeaf(const glslang::TIntermTyped* node);
227 bool isTrivial(const glslang::TIntermTyped* node);
228 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800229 spv::Id getExtBuiltins(const char* name);
John Kessenich9c14f772019-06-17 08:38:35 -0600230 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
231 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500232 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600233
John Kessenich121853f2017-05-31 17:11:16 -0600234 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600236 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700237 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 int sequenceDepth;
239
Lei Zhang17535f72016-05-04 15:55:59 -0400240 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400241
John Kessenich140f3df2015-06-26 16:58:36 -0600242 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
243 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700244 bool inEntryPoint;
245 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700246 bool linkageOnly; // true when visiting the set of objects in the AST present only for
247 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700248 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600249 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600250 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600251 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500252 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800253 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600254
John Kessenich2f273362015-07-18 22:34:27 -0600255 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700256 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
257 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600258 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700259 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700260 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800261 std::unordered_map<int, std::vector<int>> memberRemapper;
262 // for mapping glslang symbol struct to symbol Id
263 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700265 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600266 // Map pointee types for EbtReference to their forward pointers
267 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600268 // Type forcing, for when SPIR-V wants a different type than the AST,
269 // requiring local translation to and from SPIR-V type on every access.
270 // Maps <builtin-variable-id -> AST-required-type-id>
271 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600272};
273
274//
275// Helper functions for translating glslang representations to SPIR-V enumerants.
276//
277
278// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700279spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600280{
John Kessenich155d3512019-08-08 23:29:20 -0600281#ifdef GLSLANG_WEB
282 return spv::SourceLanguageESSL;
283#endif
284
John Kessenich66e2faf2016-03-12 18:34:36 -0700285 switch (source) {
286 case glslang::EShSourceGlsl:
287 switch (profile) {
288 case ENoProfile:
289 case ECoreProfile:
290 case ECompatibilityProfile:
291 return spv::SourceLanguageGLSL;
292 case EEsProfile:
293 return spv::SourceLanguageESSL;
294 default:
295 return spv::SourceLanguageUnknown;
296 }
297 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600298 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600299 default:
300 return spv::SourceLanguageUnknown;
301 }
302}
303
304// Translate glslang language (stage) to SPIR-V execution model.
305spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
306{
307 switch (stage) {
308 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600309 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600310 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600311#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600312 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
313 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
314 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700315 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
316 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
317 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
318 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
319 case EShLangMissNV: return spv::ExecutionModelMissNV;
320 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700321 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
322 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
323#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600324 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700325 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::ExecutionModelFragment;
327 }
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang sampler type to SPIR-V dimensionality.
331spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
332{
333 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700334 case glslang::Esd1D: return spv::Dim1D;
335 case glslang::Esd2D: return spv::Dim2D;
336 case glslang::Esd3D: return spv::Dim3D;
337 case glslang::EsdCube: return spv::DimCube;
338 case glslang::EsdRect: return spv::DimRect;
339 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700340 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700342 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600343 return spv::Dim2D;
344 }
345}
346
John Kessenichf6640762016-08-01 19:44:00 -0600347// Translate glslang precision to SPIR-V precision decorations.
348spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600349{
John Kessenichf6640762016-08-01 19:44:00 -0600350 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700351 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600352 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 default:
354 return spv::NoPrecision;
355 }
356}
357
John Kessenichf6640762016-08-01 19:44:00 -0600358// Translate glslang type to SPIR-V precision decorations.
359spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
360{
361 return TranslatePrecisionDecoration(type.getQualifier().precision);
362}
363
John Kessenich140f3df2015-06-26 16:58:36 -0600364// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600365spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600366{
367 if (type.getBasicType() == glslang::EbtBlock) {
368 switch (type.getQualifier().storage) {
369 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600370 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600371 case glslang::EvqVaryingIn: return spv::DecorationBlock;
372 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600373#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700374 case glslang::EvqPayloadNV: return spv::DecorationBlock;
375 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
376 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700377 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
378 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700379#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600380 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700381 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600382 break;
383 }
384 }
385
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387}
388
Rex Xu1da878f2016-02-21 20:59:01 +0800389// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700390void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
391 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800392{
Jeff Bolz36831c92018-09-05 10:11:41 -0500393 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600394 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500395 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600396 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500397 memory.push_back(spv::DecorationVolatile);
398 memory.push_back(spv::DecorationCoherent);
399 }
John Kessenich14b85d32018-06-04 15:36:03 -0600400 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600401 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800402 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600403 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800404 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600405 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800406 memory.push_back(spv::DecorationNonReadable);
407}
408
John Kessenich140f3df2015-06-26 16:58:36 -0600409// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700410spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600411{
412 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700413 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600414 case glslang::ElmRowMajor:
415 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700416 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600417 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700418 default:
419 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600420 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600421 }
422 } else {
423 switch (type.getBasicType()) {
424 default:
John Kessenich4016e382016-07-15 11:53:56 -0600425 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600426 break;
427 case glslang::EbtBlock:
428 switch (type.getQualifier().storage) {
429 case glslang::EvqUniform:
430 case glslang::EvqBuffer:
431 switch (type.getQualifier().layoutPacking) {
432 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600433 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
434 default:
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600436 }
437 case glslang::EvqVaryingIn:
438 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700439 if (type.getQualifier().isTaskMemory()) {
440 switch (type.getQualifier().layoutPacking) {
441 case glslang::ElpShared: return spv::DecorationGLSLShared;
442 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
443 default: break;
444 }
445 } else {
446 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
447 }
John Kessenich4016e382016-07-15 11:53:56 -0600448 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600449#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700450 case glslang::EvqPayloadNV:
451 case glslang::EvqPayloadInNV:
452 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700453 case glslang::EvqCallableDataNV:
454 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700455 return spv::DecorationMax;
456#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600457 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700458 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600459 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600460 }
461 }
462 }
463}
464
465// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600466// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700467// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800468spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600469{
Rex Xubbceed72016-05-21 09:40:44 +0800470 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700471 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600473 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700474 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700475 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600476 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600477 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800478 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800479 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800480 }
Rex Xubbceed72016-05-21 09:40:44 +0800481 else
John Kessenich4016e382016-07-15 11:53:56 -0600482 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800483}
484
485// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600486// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800487// should be applied.
488spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
489{
John Kessenichb9197c82019-08-11 07:41:45 -0600490 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600491 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600492#ifndef GLSLANG_WEB
493 else if (qualifier.patch)
494 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700495 else if (qualifier.sample) {
496 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600497 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600498 }
499#endif
500
501 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600502}
503
John Kessenich92187592016-02-01 13:45:25 -0700504// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700505spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600506{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700507 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600508 return spv::DecorationInvariant;
509 else
John Kessenich4016e382016-07-15 11:53:56 -0600510 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600511}
512
qining9220dbb2016-05-04 17:34:38 -0400513// If glslang type is noContraction, return SPIR-V NoContraction decoration.
514spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
515{
John Kessenichb9197c82019-08-11 07:41:45 -0600516#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600517 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400518 return spv::DecorationNoContraction;
519 else
John Kessenichb9197c82019-08-11 07:41:45 -0600520#endif
John Kessenich4016e382016-07-15 11:53:56 -0600521 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400522}
523
John Kessenich5611c6d2018-04-05 11:25:02 -0600524// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
525spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
526{
John Kessenichb9197c82019-08-11 07:41:45 -0600527#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600528 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600529 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600530 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
531 return spv::DecorationNonUniformEXT;
532 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600533#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600534 return spv::DecorationMax;
535}
536
John Kessenichb9197c82019-08-11 07:41:45 -0600537spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
538 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500539{
Jeff Bolz36831c92018-09-05 10:11:41 -0500540 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600541
542#ifndef GLSLANG_WEB
543 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
544 return mask;
545
Jeff Bolz36831c92018-09-05 10:11:41 -0500546 if (coherentFlags.volatil ||
547 coherentFlags.coherent ||
548 coherentFlags.devicecoherent ||
549 coherentFlags.queuefamilycoherent ||
550 coherentFlags.workgroupcoherent ||
551 coherentFlags.subgroupcoherent) {
552 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
553 spv::MemoryAccessMakePointerVisibleKHRMask;
554 }
555 if (coherentFlags.nonprivate) {
556 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
557 }
558 if (coherentFlags.volatil) {
559 mask = mask | spv::MemoryAccessVolatileMask;
560 }
561 if (mask != spv::MemoryAccessMaskNone) {
562 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
563 }
John Kessenichb9197c82019-08-11 07:41:45 -0600564#endif
565
Jeff Bolz36831c92018-09-05 10:11:41 -0500566 return mask;
567}
568
John Kessenichb9197c82019-08-11 07:41:45 -0600569spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
570 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500571{
Jeff Bolz36831c92018-09-05 10:11:41 -0500572 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600573
574#ifndef GLSLANG_WEB
575 if (!glslangIntermediate->usingVulkanMemoryModel())
576 return mask;
577
Jeff Bolz36831c92018-09-05 10:11:41 -0500578 if (coherentFlags.volatil ||
579 coherentFlags.coherent ||
580 coherentFlags.devicecoherent ||
581 coherentFlags.queuefamilycoherent ||
582 coherentFlags.workgroupcoherent ||
583 coherentFlags.subgroupcoherent) {
584 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
585 spv::ImageOperandsMakeTexelVisibleKHRMask;
586 }
587 if (coherentFlags.nonprivate) {
588 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
589 }
590 if (coherentFlags.volatil) {
591 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
592 }
593 if (mask != spv::ImageOperandsMaskNone) {
594 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
595 }
John Kessenichb9197c82019-08-11 07:41:45 -0600596#endif
597
Jeff Bolz36831c92018-09-05 10:11:41 -0500598 return mask;
599}
600
601spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
602{
John Kessenichb9197c82019-08-11 07:41:45 -0600603 spv::Builder::AccessChain::CoherentFlags flags = {};
604#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500605 flags.coherent = type.getQualifier().coherent;
606 flags.devicecoherent = type.getQualifier().devicecoherent;
607 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
608 // shared variables are implicitly workgroupcoherent in GLSL.
609 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
610 type.getQualifier().storage == glslang::EvqShared;
611 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600612 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500613 // *coherent variables are implicitly nonprivate in GLSL
614 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500615 flags.subgroupcoherent ||
616 flags.workgroupcoherent ||
617 flags.queuefamilycoherent ||
618 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600619 flags.coherent ||
620 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500621 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600622#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500623 return flags;
624}
625
John Kessenichb9197c82019-08-11 07:41:45 -0600626spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
627 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500628{
John Kessenichb9197c82019-08-11 07:41:45 -0600629 spv::Scope scope = spv::ScopeMax;
630
631#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600632 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500633 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
634 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
635 } else if (coherentFlags.devicecoherent) {
636 scope = spv::ScopeDevice;
637 } else if (coherentFlags.queuefamilycoherent) {
638 scope = spv::ScopeQueueFamilyKHR;
639 } else if (coherentFlags.workgroupcoherent) {
640 scope = spv::ScopeWorkgroup;
641 } else if (coherentFlags.subgroupcoherent) {
642 scope = spv::ScopeSubgroup;
Jeff Bolz36831c92018-09-05 10:11:41 -0500643 }
644 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
645 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
646 }
John Kessenichb9197c82019-08-11 07:41:45 -0600647#endif
648
Jeff Bolz36831c92018-09-05 10:11:41 -0500649 return scope;
650}
651
David Netoa901ffe2016-06-08 14:11:40 +0100652// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
653// associated capabilities when required. For some built-in variables, a capability
654// is generated only when using the variable in an executable instruction, but not when
655// just declaring a struct member variable with it. This is true for PointSize,
656// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700657spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
658 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600659{
660 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700661 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600662#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600663 // Defer adding the capability until the built-in is actually used.
664 if (! memberDeclaration) {
665 switch (glslangIntermediate->getStage()) {
666 case EShLangGeometry:
667 builder.addCapability(spv::CapabilityGeometryPointSize);
668 break;
669 case EShLangTessControl:
670 case EShLangTessEvaluation:
671 builder.addCapability(spv::CapabilityTessellationPointSize);
672 break;
673 default:
674 break;
675 }
John Kessenich92187592016-02-01 13:45:25 -0700676 }
John Kessenich155d3512019-08-08 23:29:20 -0600677#endif
John Kessenich92187592016-02-01 13:45:25 -0700678 return spv::BuiltInPointSize;
679
John Kessenicha28f7a72019-08-06 07:00:58 -0600680 case glslang::EbvPosition: return spv::BuiltInPosition;
681 case glslang::EbvVertexId: return spv::BuiltInVertexId;
682 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
683 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
684 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
685
686 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
687 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
688 case glslang::EbvFace: return spv::BuiltInFrontFacing;
689 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
690
John Kessenich3dd1ce52019-10-17 07:08:40 -0600691 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
692 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
693 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
694 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
695 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
696 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
697
John Kessenicha28f7a72019-08-06 07:00:58 -0600698#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600699 // These *Distance capabilities logically belong here, but if the member is declared and
700 // then never used, consumers of SPIR-V prefer the capability not be declared.
701 // They are now generated when used, rather than here when declared.
702 // Potentially, the specification should be more clear what the minimum
703 // use needed is to trigger the capability.
704 //
John Kessenich92187592016-02-01 13:45:25 -0700705 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100706 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800707 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700708 return spv::BuiltInClipDistance;
709
710 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100711 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800712 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700713 return spv::BuiltInCullDistance;
714
715 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600716 builder.addCapability(spv::CapabilityMultiViewport);
717 if (glslangIntermediate->getStage() == EShLangVertex ||
718 glslangIntermediate->getStage() == EShLangTessControl ||
719 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800720
John Kessenich8317e6c2019-08-18 23:58:08 -0600721 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600722 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800723 }
John Kessenich92187592016-02-01 13:45:25 -0700724 return spv::BuiltInViewportIndex;
725
John Kessenich5e801132016-02-15 11:09:46 -0700726 case glslang::EbvSampleId:
727 builder.addCapability(spv::CapabilitySampleRateShading);
728 return spv::BuiltInSampleId;
729
730 case glslang::EbvSamplePosition:
731 builder.addCapability(spv::CapabilitySampleRateShading);
732 return spv::BuiltInSamplePosition;
733
734 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700735 return spv::BuiltInSampleMask;
736
John Kessenich78a45572016-07-08 14:05:15 -0600737 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700738 if (glslangIntermediate->getStage() == EShLangMeshNV) {
739 return spv::BuiltInLayer;
740 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600741 builder.addCapability(spv::CapabilityGeometry);
742 if (glslangIntermediate->getStage() == EShLangVertex ||
743 glslangIntermediate->getStage() == EShLangTessControl ||
744 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800745
John Kessenich8317e6c2019-08-18 23:58:08 -0600746 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600747 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800748 }
John Kessenich78a45572016-07-08 14:05:15 -0600749 return spv::BuiltInLayer;
750
John Kessenichda581a22015-10-14 14:10:30 -0600751 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600752 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800753 builder.addCapability(spv::CapabilityDrawParameters);
754 return spv::BuiltInBaseVertex;
755
John Kessenichda581a22015-10-14 14:10:30 -0600756 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600757 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800758 builder.addCapability(spv::CapabilityDrawParameters);
759 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200760
John Kessenichda581a22015-10-14 14:10:30 -0600761 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600762 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800763 builder.addCapability(spv::CapabilityDrawParameters);
764 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200765
766 case glslang::EbvPrimitiveId:
767 if (glslangIntermediate->getStage() == EShLangFragment)
768 builder.addCapability(spv::CapabilityGeometry);
769 return spv::BuiltInPrimitiveId;
770
Rex Xu37cdcee2017-06-29 17:46:34 +0800771 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800772 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
773 builder.addCapability(spv::CapabilityStencilExportEXT);
774 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800775
John Kessenich140f3df2015-06-26 16:58:36 -0600776 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600777 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
778 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
779 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
780 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600781 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800782
Rex Xu574ab042016-04-14 16:53:07 +0800783 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800784 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800785 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
786 return spv::BuiltInSubgroupSize;
787
Rex Xu574ab042016-04-14 16:53:07 +0800788 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800789 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800790 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
791 return spv::BuiltInSubgroupLocalInvocationId;
792
Rex Xu574ab042016-04-14 16:53:07 +0800793 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800794 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
795 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600796 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800797
Rex Xu574ab042016-04-14 16:53:07 +0800798 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800799 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
800 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600801 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800802
Rex Xu574ab042016-04-14 16:53:07 +0800803 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800804 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
805 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600806 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800807
Rex Xu574ab042016-04-14 16:53:07 +0800808 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800809 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
810 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600811 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800812
Rex Xu574ab042016-04-14 16:53:07 +0800813 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800814 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
815 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600816 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800817
John Kessenich66011cb2018-03-06 16:12:04 -0700818 case glslang::EbvNumSubgroups:
819 builder.addCapability(spv::CapabilityGroupNonUniform);
820 return spv::BuiltInNumSubgroups;
821
822 case glslang::EbvSubgroupID:
823 builder.addCapability(spv::CapabilityGroupNonUniform);
824 return spv::BuiltInSubgroupId;
825
826 case glslang::EbvSubgroupSize2:
827 builder.addCapability(spv::CapabilityGroupNonUniform);
828 return spv::BuiltInSubgroupSize;
829
830 case glslang::EbvSubgroupInvocation2:
831 builder.addCapability(spv::CapabilityGroupNonUniform);
832 return spv::BuiltInSubgroupLocalInvocationId;
833
834 case glslang::EbvSubgroupEqMask2:
835 builder.addCapability(spv::CapabilityGroupNonUniform);
836 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
837 return spv::BuiltInSubgroupEqMask;
838
839 case glslang::EbvSubgroupGeMask2:
840 builder.addCapability(spv::CapabilityGroupNonUniform);
841 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
842 return spv::BuiltInSubgroupGeMask;
843
844 case glslang::EbvSubgroupGtMask2:
845 builder.addCapability(spv::CapabilityGroupNonUniform);
846 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
847 return spv::BuiltInSubgroupGtMask;
848
849 case glslang::EbvSubgroupLeMask2:
850 builder.addCapability(spv::CapabilityGroupNonUniform);
851 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
852 return spv::BuiltInSubgroupLeMask;
853
854 case glslang::EbvSubgroupLtMask2:
855 builder.addCapability(spv::CapabilityGroupNonUniform);
856 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
857 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600858
Rex Xu17ff3432016-10-14 17:41:45 +0800859 case glslang::EbvBaryCoordNoPersp:
860 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
861 return spv::BuiltInBaryCoordNoPerspAMD;
862
863 case glslang::EbvBaryCoordNoPerspCentroid:
864 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
865 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
866
867 case glslang::EbvBaryCoordNoPerspSample:
868 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
869 return spv::BuiltInBaryCoordNoPerspSampleAMD;
870
871 case glslang::EbvBaryCoordSmooth:
872 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
873 return spv::BuiltInBaryCoordSmoothAMD;
874
875 case glslang::EbvBaryCoordSmoothCentroid:
876 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
877 return spv::BuiltInBaryCoordSmoothCentroidAMD;
878
879 case glslang::EbvBaryCoordSmoothSample:
880 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
881 return spv::BuiltInBaryCoordSmoothSampleAMD;
882
883 case glslang::EbvBaryCoordPullModel:
884 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
885 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800886
John Kessenich6c8aaac2017-02-27 01:20:51 -0700887 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600888 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700889 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700890 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700891
892 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600893 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700894 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700895 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700896
Daniel Koch5154db52018-11-26 10:01:58 -0500897 case glslang::EbvFragSizeEXT:
898 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
899 builder.addCapability(spv::CapabilityFragmentDensityEXT);
900 return spv::BuiltInFragSizeEXT;
901
902 case glslang::EbvFragInvocationCountEXT:
903 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
904 builder.addCapability(spv::CapabilityFragmentDensityEXT);
905 return spv::BuiltInFragInvocationCountEXT;
906
chaoc771d89f2017-01-13 01:10:53 -0800907 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800908 if (!memberDeclaration) {
909 builder.addExtension(spv::E_SPV_NV_viewport_array2);
910 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
911 }
chaoc771d89f2017-01-13 01:10:53 -0800912 return spv::BuiltInViewportMaskNV;
913 case glslang::EbvSecondaryPositionNV:
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::BuiltInSecondaryPositionNV;
919 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800920 if (!memberDeclaration) {
921 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
922 builder.addCapability(spv::CapabilityShaderStereoViewNV);
923 }
chaoc771d89f2017-01-13 01:10:53 -0800924 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800925 case glslang::EbvPositionPerViewNV:
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::BuiltInPositionPerViewNV;
931 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800932 if (!memberDeclaration) {
933 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
934 builder.addCapability(spv::CapabilityPerViewAttributesNV);
935 }
chaocdf3956c2017-02-14 14:52:34 -0800936 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700937 case glslang::EbvFragFullyCoveredNV:
938 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
939 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
940 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700941 case glslang::EbvFragmentSizeNV:
942 builder.addExtension(spv::E_SPV_NV_shading_rate);
943 builder.addCapability(spv::CapabilityShadingRateNV);
944 return spv::BuiltInFragmentSizeNV;
945 case glslang::EbvInvocationsPerPixelNV:
946 builder.addExtension(spv::E_SPV_NV_shading_rate);
947 builder.addCapability(spv::CapabilityShadingRateNV);
948 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700949
Daniel Koch593a4e02019-05-27 16:46:31 -0400950 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700951 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700952 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700953 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700954 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700955 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700956 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700957 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700958 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700959 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700960 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700961 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700962 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700963 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700964 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700965 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700966 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700967 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700968 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700969 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700970 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700971 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700972 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700973 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700974 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700975 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700976 return spv::BuiltInWorldToObjectNV;
977 case glslang::EbvIncomingRayFlagsNV:
978 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400979
980 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700981 case glslang::EbvBaryCoordNV:
982 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
983 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
984 return spv::BuiltInBaryCoordNV;
985 case glslang::EbvBaryCoordNoPerspNV:
986 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
987 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
988 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400989
990 // mesh shaders
991 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700992 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400993 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700994 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400995 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700996 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400997 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700998 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001000 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001001 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001003 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001004 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001005 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001006 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001007
1008 // sm builtins
1009 case glslang::EbvWarpsPerSM:
1010 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1011 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1012 return spv::BuiltInWarpsPerSMNV;
1013 case glslang::EbvSMCount:
1014 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1015 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1016 return spv::BuiltInSMCountNV;
1017 case glslang::EbvWarpID:
1018 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1019 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1020 return spv::BuiltInWarpIDNV;
1021 case glslang::EbvSMID:
1022 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1023 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1024 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001025#endif
1026
Rex Xu3e783f92017-02-22 16:44:48 +08001027 default:
1028 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001029 }
1030}
1031
Rex Xufc618912015-09-09 16:42:49 +08001032// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001033spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001034{
1035 assert(type.getBasicType() == glslang::EbtSampler);
1036
John Kessenichb9197c82019-08-11 07:41:45 -06001037#ifdef GLSLANG_WEB
1038 return spv::ImageFormatUnknown;
1039#endif
1040
John Kessenich5d0fa972016-02-15 11:57:00 -07001041 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001042 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001043 case glslang::ElfRg32f:
1044 case glslang::ElfRg16f:
1045 case glslang::ElfR11fG11fB10f:
1046 case glslang::ElfR16f:
1047 case glslang::ElfRgba16:
1048 case glslang::ElfRgb10A2:
1049 case glslang::ElfRg16:
1050 case glslang::ElfRg8:
1051 case glslang::ElfR16:
1052 case glslang::ElfR8:
1053 case glslang::ElfRgba16Snorm:
1054 case glslang::ElfRg16Snorm:
1055 case glslang::ElfRg8Snorm:
1056 case glslang::ElfR16Snorm:
1057 case glslang::ElfR8Snorm:
1058
1059 case glslang::ElfRg32i:
1060 case glslang::ElfRg16i:
1061 case glslang::ElfRg8i:
1062 case glslang::ElfR16i:
1063 case glslang::ElfR8i:
1064
1065 case glslang::ElfRgb10a2ui:
1066 case glslang::ElfRg32ui:
1067 case glslang::ElfRg16ui:
1068 case glslang::ElfRg8ui:
1069 case glslang::ElfR16ui:
1070 case glslang::ElfR8ui:
1071 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1072 break;
1073
1074 default:
1075 break;
1076 }
1077
1078 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001079 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001080 case glslang::ElfNone: return spv::ImageFormatUnknown;
1081 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1082 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1083 case glslang::ElfR32f: return spv::ImageFormatR32f;
1084 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1085 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1086 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1087 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1088 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1089 case glslang::ElfR16f: return spv::ImageFormatR16f;
1090 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1091 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1092 case glslang::ElfRg16: return spv::ImageFormatRg16;
1093 case glslang::ElfRg8: return spv::ImageFormatRg8;
1094 case glslang::ElfR16: return spv::ImageFormatR16;
1095 case glslang::ElfR8: return spv::ImageFormatR8;
1096 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1097 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1098 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1099 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1100 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1101 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1102 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1103 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1104 case glslang::ElfR32i: return spv::ImageFormatR32i;
1105 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1106 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1107 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1108 case glslang::ElfR16i: return spv::ImageFormatR16i;
1109 case glslang::ElfR8i: return spv::ImageFormatR8i;
1110 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1111 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1112 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1113 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1114 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1115 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1116 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1117 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1118 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1119 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001120 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001121 }
1122}
1123
John Kessenich8985fc92020-03-03 10:25:07 -07001124spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1125 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001126{
John Kesseniche18fd202018-01-30 11:01:39 -07001127 if (selectionNode.getFlatten())
1128 return spv::SelectionControlFlattenMask;
1129 if (selectionNode.getDontFlatten())
1130 return spv::SelectionControlDontFlattenMask;
1131 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001132}
1133
John Kessenich8985fc92020-03-03 10:25:07 -07001134spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1135 const
steve-lunargf1709e72017-05-02 20:14:50 -06001136{
John Kesseniche18fd202018-01-30 11:01:39 -07001137 if (switchNode.getFlatten())
1138 return spv::SelectionControlFlattenMask;
1139 if (switchNode.getDontFlatten())
1140 return spv::SelectionControlDontFlattenMask;
1141 return spv::SelectionControlMaskNone;
1142}
1143
John Kessenicha2858d92018-01-31 08:11:18 -07001144// return a non-0 dependency if the dependency argument must be set
1145spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001146 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001147{
1148 spv::LoopControlMask control = spv::LoopControlMaskNone;
1149
1150 if (loopNode.getDontUnroll())
1151 control = control | spv::LoopControlDontUnrollMask;
1152 if (loopNode.getUnroll())
1153 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001154 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001155 control = control | spv::LoopControlDependencyInfiniteMask;
1156 else if (loopNode.getLoopDependency() > 0) {
1157 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001158 operands.push_back((unsigned int)loopNode.getLoopDependency());
1159 }
1160 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1161 if (loopNode.getMinIterations() > 0) {
1162 control = control | spv::LoopControlMinIterationsMask;
1163 operands.push_back(loopNode.getMinIterations());
1164 }
1165 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1166 control = control | spv::LoopControlMaxIterationsMask;
1167 operands.push_back(loopNode.getMaxIterations());
1168 }
1169 if (loopNode.getIterationMultiple() > 1) {
1170 control = control | spv::LoopControlIterationMultipleMask;
1171 operands.push_back(loopNode.getIterationMultiple());
1172 }
1173 if (loopNode.getPeelCount() > 0) {
1174 control = control | spv::LoopControlPeelCountMask;
1175 operands.push_back(loopNode.getPeelCount());
1176 }
1177 if (loopNode.getPartialCount() > 0) {
1178 control = control | spv::LoopControlPartialCountMask;
1179 operands.push_back(loopNode.getPartialCount());
1180 }
John Kessenicha2858d92018-01-31 08:11:18 -07001181 }
John Kesseniche18fd202018-01-30 11:01:39 -07001182
1183 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001184}
1185
John Kessenicha5c5fb62017-05-05 05:09:58 -06001186// Translate glslang type to SPIR-V storage class.
1187spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1188{
1189 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() &&
John Kessenichdeec1932019-08-13 08:00:30 -06001203 type.getQualifier().isShaderRecordNV()) {
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001204 return spv::StorageClassShaderRecordBufferNV;
1205 }
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
Ashwin Leleff1783d2018-10-22 16:41:44 -07001226 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1227 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1228 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1229 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1230 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
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() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001290 ! type.getQualifier().isShaderRecordNV() &&
1291 ! 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.
1297 if (type.getBasicType() == glslang::EbtSampler)
1298 return type.getQualifier().isUniformOrBuffer();
1299
1300 // None of the above.
1301 return false;
1302}
1303
John Kesseniche0b6cad2015-12-24 10:30:13 -07001304void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1305{
1306 if (child.layoutMatrix == glslang::ElmNone)
1307 child.layoutMatrix = parent.layoutMatrix;
1308
1309 if (parent.invariant)
1310 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001311 if (parent.flat)
1312 child.flat = true;
1313 if (parent.centroid)
1314 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001315#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001316 if (parent.nopersp)
1317 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001318 if (parent.explicitInterp)
1319 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001320 if (parent.perPrimitiveNV)
1321 child.perPrimitiveNV = true;
1322 if (parent.perViewNV)
1323 child.perViewNV = true;
1324 if (parent.perTaskNV)
1325 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001326 if (parent.patch)
1327 child.patch = true;
1328 if (parent.sample)
1329 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001330 if (parent.coherent)
1331 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001332 if (parent.devicecoherent)
1333 child.devicecoherent = true;
1334 if (parent.queuefamilycoherent)
1335 child.queuefamilycoherent = true;
1336 if (parent.workgroupcoherent)
1337 child.workgroupcoherent = true;
1338 if (parent.subgroupcoherent)
1339 child.subgroupcoherent = true;
1340 if (parent.nonprivate)
1341 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001342 if (parent.volatil)
1343 child.volatil = true;
1344 if (parent.restrict)
1345 child.restrict = true;
1346 if (parent.readonly)
1347 child.readonly = true;
1348 if (parent.writeonly)
1349 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001350#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001351}
1352
John Kessenichf2b7f332016-09-01 17:05:23 -06001353bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001354{
John Kessenich7b9fa252016-01-21 18:56:57 -07001355 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001356 // - struct members might inherit from a struct declaration
1357 // (note that non-block structs don't explicitly inherit,
1358 // only implicitly, meaning no decoration involved)
1359 // - affect decorations on the struct members
1360 // (note smooth does not, and expecting something like volatile
1361 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001362 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001363 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001364}
1365
John Kessenich140f3df2015-06-26 16:58:36 -06001366//
1367// Implement the TGlslangToSpvTraverser class.
1368//
1369
John Kessenich8985fc92020-03-03 10:25:07 -07001370TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1371 const glslang::TIntermediate* glslangIntermediate,
1372 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1373 TIntermTraverser(true, false, true),
1374 options(options),
1375 shaderEntry(nullptr), currentFunction(nullptr),
1376 sequenceDepth(0), logger(buildLogger),
1377 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1378 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1379 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001380 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1381 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001382{
1383 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1384
1385 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001386 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1387 glslangIntermediate->getVersion());
1388
John Kessenich121853f2017-05-31 17:11:16 -06001389 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001390 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001391 builder.setSourceFile(glslangIntermediate->getSourceFile());
1392
1393 // Set the source shader's text. If for SPV version 1.0, include
1394 // a preamble in comments stating the OpModuleProcessed instructions.
1395 // Otherwise, emit those as actual instructions.
1396 std::string text;
1397 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1398 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001399 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001400 text.append("// OpModuleProcessed ");
1401 text.append(processes[p]);
1402 text.append("\n");
1403 } else
1404 builder.addModuleProcessed(processes[p]);
1405 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001406 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001407 text.append("#line 1\n");
1408 text.append(glslangIntermediate->getSourceText());
1409 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001410 // Pass name and text for all included files
1411 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1412 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1413 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001414 }
John Kessenich140f3df2015-06-26 16:58:36 -06001415 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001416
1417 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1418 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1419
1420 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1421 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001422 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001423 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001424 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001425 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001426 memoryModel = spv::MemoryModelVulkanKHR;
1427 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001428 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001429 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001430 builder.setMemoryModel(addressingModel, memoryModel);
1431
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001432 if (glslangIntermediate->usingVariablePointers()) {
1433 builder.addCapability(spv::CapabilityVariablePointers);
1434 }
1435
John Kessenicheee9d532016-09-19 18:09:30 -06001436 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1437 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001440 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1441 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001442 builder.addSourceExtension(it->c_str());
1443
1444 // Add the top-level modes for this shader.
1445
John Kessenich92187592016-02-01 13:45:25 -07001446 if (glslangIntermediate->getXfbMode()) {
1447 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001449 }
John Kessenich140f3df2015-06-26 16:58:36 -06001450
1451 unsigned int mode;
1452 switch (glslangIntermediate->getStage()) {
1453 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001454 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001455 break;
1456
John Kessenicha28f7a72019-08-06 07:00:58 -06001457 case EShLangFragment:
1458 builder.addCapability(spv::CapabilityShader);
1459 if (glslangIntermediate->getPixelCenterInteger())
1460 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1461
1462 if (glslangIntermediate->getOriginUpperLeft())
1463 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1464 else
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1466
1467 if (glslangIntermediate->getEarlyFragmentTests())
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1469
1470 if (glslangIntermediate->getPostDepthCoverage()) {
1471 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1473 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1474 }
1475
John Kessenichb9197c82019-08-11 07:41:45 -06001476 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1478
1479#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001480 switch(glslangIntermediate->getDepth()) {
1481 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1482 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1483 default: mode = spv::ExecutionModeMax; break;
1484 }
1485 if (mode != spv::ExecutionModeMax)
1486 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001487 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001488 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1489 break;
1490 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1491 break;
1492 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1493 break;
1494 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1495 break;
1496 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1497 break;
1498 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1499 break;
1500 default: mode = spv::ExecutionModeMax;
1501 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001502 }
1503 if (mode != spv::ExecutionModeMax) {
1504 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1505 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1506 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1507 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1508 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1509 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1510 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1511 } else {
1512 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1513 }
1514 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1515 }
John Kessenichb9197c82019-08-11 07:41:45 -06001516#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001517 break;
1518
John Kessenicha28f7a72019-08-06 07:00:58 -06001519 case EShLangCompute:
1520 builder.addCapability(spv::CapabilityShader);
1521 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1522 glslangIntermediate->getLocalSize(1),
1523 glslangIntermediate->getLocalSize(2));
1524 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1525 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1526 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1527 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1528 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1529 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1530 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1531 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1532 }
1533 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001534#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001535 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001536 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001537 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001538
steve-lunarge7412492017-03-23 11:56:07 -06001539 glslang::TLayoutGeometry primitive;
1540
1541 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001542 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1543 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001544 primitive = glslangIntermediate->getOutputPrimitive();
1545 } else {
1546 primitive = glslangIntermediate->getInputPrimitive();
1547 }
1548
1549 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001550 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1551 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1552 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001553 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001554 }
John Kessenich4016e382016-07-15 11:53:56 -06001555 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001556 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1557
John Kesseniche6903322015-10-13 16:29:02 -06001558 switch (glslangIntermediate->getVertexSpacing()) {
1559 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1560 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1561 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001562 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001563 }
John Kessenich4016e382016-07-15 11:53:56 -06001564 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001565 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1566
1567 switch (glslangIntermediate->getVertexOrder()) {
1568 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1569 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; 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 if (glslangIntermediate->getPointMode())
1576 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001577 break;
1578
1579 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001580 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001581 switch (glslangIntermediate->getInputPrimitive()) {
1582 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1583 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1584 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001585 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001586 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001587 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001588 }
John Kessenich4016e382016-07-15 11:53:56 -06001589 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001590 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001591
John Kessenich140f3df2015-06-26 16:58:36 -06001592 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1593
1594 switch (glslangIntermediate->getOutputPrimitive()) {
1595 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1596 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1597 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001598 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001599 }
John Kessenich4016e382016-07-15 11:53:56 -06001600 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001601 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1602 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1603 break;
1604
Chao Chenb50c02e2018-09-19 11:42:24 -07001605 case EShLangRayGenNV:
1606 case EShLangIntersectNV:
1607 case EShLangAnyHitNV:
1608 case EShLangClosestHitNV:
1609 case EShLangMissNV:
1610 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001611 builder.addCapability(spv::CapabilityRayTracingNV);
1612 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001613 break;
Chao Chen3c366992018-09-19 11:41:59 -07001614 case EShLangTaskNV:
1615 case EShLangMeshNV:
1616 builder.addCapability(spv::CapabilityMeshShadingNV);
1617 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1618 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1619 glslangIntermediate->getLocalSize(1),
1620 glslangIntermediate->getLocalSize(2));
1621 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001622 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1623 glslangIntermediate->getVertices());
1624 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1625 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001626
1627 switch (glslangIntermediate->getOutputPrimitive()) {
1628 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1629 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1630 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1631 default: mode = spv::ExecutionModeMax; break;
1632 }
1633 if (mode != spv::ExecutionModeMax)
1634 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1635 }
1636 break;
1637#endif
1638
John Kessenich140f3df2015-06-26 16:58:36 -06001639 default:
1640 break;
1641 }
John Kessenich140f3df2015-06-26 16:58:36 -06001642}
1643
John Kessenichfca82622016-11-26 13:23:20 -07001644// Finish creating SPV, after the traversal is complete.
1645void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001646{
John Kessenichf04c51b2018-08-03 15:56:12 -06001647 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001648 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001649 builder.setBuildPoint(shaderEntry->getLastBlock());
1650 builder.leaveFunction();
1651 }
1652
John Kessenich7ba63412015-12-20 17:37:07 -07001653 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001654 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1655 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001656
David Neto8c3d5b42019-10-21 14:50:31 -04001657 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001658 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001659 // Note: WebGPU code generation must have the opportunity to aggressively
1660 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001661 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001662}
1663
John Kessenichfca82622016-11-26 13:23:20 -07001664// Write the SPV into 'out'.
1665void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001666{
John Kessenichfca82622016-11-26 13:23:20 -07001667 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001668}
1669
1670//
1671// Implement the traversal functions.
1672//
1673// Return true from interior nodes to have the external traversal
1674// continue on to children. Return false if children were
1675// already processed.
1676//
1677
1678//
qining25262b32016-05-06 17:25:16 -04001679// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001680// - uniform/input reads
1681// - output writes
1682// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1683// - something simple that degenerates into the last bullet
1684//
1685void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1686{
qining75d1d802016-04-06 14:42:01 -04001687 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001688 if (symbol->getType().isStruct())
1689 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1690
qining75d1d802016-04-06 14:42:01 -04001691 if (symbol->getType().getQualifier().isSpecConstant())
1692 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1693
John Kessenich140f3df2015-06-26 16:58:36 -06001694 // getSymbolId() will set up all the IO decorations on the first call.
1695 // Formal function parameters were mapped during makeFunctions().
1696 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001697
John Kessenich7ba63412015-12-20 17:37:07 -07001698 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001699 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001700 // Consider adding to the OpEntryPoint interface list.
1701 // Only looking at structures if they have at least one member.
1702 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1703 spv::StorageClass sc = builder.getStorageClass(id);
1704 // Before SPIR-V 1.4, we only want to include Input and Output.
1705 // Starting with SPIR-V 1.4, we want all globals.
1706 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1707 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001708 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001709 }
John Kessenich5f77d862017-09-19 11:09:59 -06001710 }
John Kessenich9c14f772019-06-17 08:38:35 -06001711
1712 // If the SPIR-V type is required to be different than the AST type,
1713 // translate now from the SPIR-V type to the AST type, for the consuming
1714 // operation.
1715 // Note this turns it from an l-value to an r-value.
1716 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1717 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1718 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001719 }
1720
1721 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001722 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001723 // Prepare to generate code for the access
1724
1725 // L-value chains will be computed left to right. We're on the symbol now,
1726 // which is the left-most part of the access chain, so now is "clear" time,
1727 // followed by setting the base.
1728 builder.clearAccessChain();
1729
1730 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001731 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001732 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001733 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001734 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001735 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001736 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001737 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001738 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1739 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001740 builder.setAccessChainRValue(id);
1741 else
1742 builder.setAccessChainLValue(id);
1743 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001744
John Kessenichb9197c82019-08-11 07:41:45 -06001745#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001746 // Process linkage-only nodes for any special additional interface work.
1747 if (linkageOnly) {
1748 if (glslangIntermediate->getHlslFunctionality1()) {
1749 // Map implicit counter buffers to their originating buffers, which should have been
1750 // seen by now, given earlier pruning of unused counters, and preservation of order
1751 // of declaration.
1752 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1753 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1754 // Save possible originating buffers for counter buffers, keyed by
1755 // making the potential counter-buffer name.
1756 std::string keyName = symbol->getName().c_str();
1757 keyName = glslangIntermediate->addCounterBufferName(keyName);
1758 counterOriginator[keyName] = symbol;
1759 } else {
1760 // Handle a counter buffer, by finding the saved originating buffer.
1761 std::string keyName = symbol->getName().c_str();
1762 auto it = counterOriginator.find(keyName);
1763 if (it != counterOriginator.end()) {
1764 id = getSymbolId(it->second);
1765 if (id != spv::NoResult) {
1766 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001767 if (counterId != spv::NoResult) {
1768 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001769 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001770 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001771 }
1772 }
1773 }
1774 }
1775 }
1776 }
John Kessenich155d3512019-08-08 23:29:20 -06001777#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001778}
1779
1780bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1781{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001782 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001783 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1784 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1785 }
1786 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1787 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1788 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001789
qining40887662016-04-03 22:20:42 -04001790 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1791 if (node->getType().getQualifier().isSpecConstant())
1792 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1793
John Kessenich140f3df2015-06-26 16:58:36 -06001794 // First, handle special cases
1795 switch (node->getOp()) {
1796 case glslang::EOpAssign:
1797 case glslang::EOpAddAssign:
1798 case glslang::EOpSubAssign:
1799 case glslang::EOpMulAssign:
1800 case glslang::EOpVectorTimesMatrixAssign:
1801 case glslang::EOpVectorTimesScalarAssign:
1802 case glslang::EOpMatrixTimesScalarAssign:
1803 case glslang::EOpMatrixTimesMatrixAssign:
1804 case glslang::EOpDivAssign:
1805 case glslang::EOpModAssign:
1806 case glslang::EOpAndAssign:
1807 case glslang::EOpInclusiveOrAssign:
1808 case glslang::EOpExclusiveOrAssign:
1809 case glslang::EOpLeftShiftAssign:
1810 case glslang::EOpRightShiftAssign:
1811 // A bin-op assign "a += b" means the same thing as "a = a + b"
1812 // where a is evaluated before b. For a simple assignment, GLSL
1813 // says to evaluate the left before the right. So, always, left
1814 // node then right node.
1815 {
1816 // get the left l-value, save it away
1817 builder.clearAccessChain();
1818 node->getLeft()->traverse(this);
1819 spv::Builder::AccessChain lValue = builder.getAccessChain();
1820
1821 // evaluate the right
1822 builder.clearAccessChain();
1823 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001824 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001825
1826 if (node->getOp() != glslang::EOpAssign) {
1827 // the left is also an r-value
1828 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001829 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001830
1831 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001832 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001833 TranslateNoContractionDecoration(node->getType().getQualifier()),
1834 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001835 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001836 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1837 node->getType().getBasicType());
1838
1839 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001840 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001841 }
1842
1843 // store the result
1844 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001845 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001846
1847 // assignments are expressions having an rValue after they are evaluated...
1848 builder.clearAccessChain();
1849 builder.setAccessChainRValue(rValue);
1850 }
1851 return false;
1852 case glslang::EOpIndexDirect:
1853 case glslang::EOpIndexDirectStruct:
1854 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001855 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001856 // Get the left part of the access chain.
1857 node->getLeft()->traverse(this);
1858
1859 // Add the next element in the chain
1860
David Netoa901ffe2016-06-08 14:11:40 +01001861 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001862 if (! node->getLeft()->getType().isArray() &&
1863 node->getLeft()->getType().isVector() &&
1864 node->getOp() == glslang::EOpIndexDirect) {
1865 // This is essentially a hard-coded vector swizzle of size 1,
1866 // so short circuit the access-chain stuff with a swizzle.
1867 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001868 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001869 int dummySize;
1870 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1871 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001872 glslangIntermediate->getBaseAlignmentScalar(
1873 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001874 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001875
1876 // Load through a block reference is performed with a dot operator that
1877 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1878 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001879 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001880 !node->getLeft()->getType().isArray() &&
1881 node->getOp() == glslang::EOpIndexDirectStruct)
1882 {
1883 spv::Id left = accessChainLoad(node->getLeft()->getType());
1884 builder.clearAccessChain();
1885 builder.setAccessChainLValue(left);
1886 }
1887
David Netoa901ffe2016-06-08 14:11:40 +01001888 int spvIndex = glslangIndex;
1889 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1890 node->getOp() == glslang::EOpIndexDirectStruct)
1891 {
1892 // This may be, e.g., an anonymous block-member selection, which generally need
1893 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001894 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1895 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1896 std::vector<int>& remapper = memberRemapper[glslangId];
1897 assert(remapper.size() > 0);
1898 spvIndex = remapper[glslangIndex];
1899 }
David Netoa901ffe2016-06-08 14:11:40 +01001900 }
John Kessenichebb50532016-05-16 19:22:05 -06001901
David Netoa901ffe2016-06-08 14:11:40 +01001902 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001903 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1904 TranslateCoherent(node->getLeft()->getType()),
1905 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001906
1907 // Add capabilities here for accessing PointSize and clip/cull distance.
1908 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001909 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001910 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001911 }
1912 }
1913 return false;
1914 case glslang::EOpIndexIndirect:
1915 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001916 // Array, matrix, or vector indirection with variable index.
1917 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001918 // matrices are arrays of vectors, so will also work for a matrix.
1919 // Will use the access chain's 'component' for variable index into a vector.
1920
1921 // This adapter is building access chains left to right.
1922 // Set up the access chain to the left.
1923 node->getLeft()->traverse(this);
1924
1925 // save it so that computing the right side doesn't trash it
1926 spv::Builder::AccessChain partial = builder.getAccessChain();
1927
1928 // compute the next index in the chain
1929 builder.clearAccessChain();
1930 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001931 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001932
John Kessenich5611c6d2018-04-05 11:25:02 -06001933 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1934
John Kessenich140f3df2015-06-26 16:58:36 -06001935 // restore the saved access chain
1936 builder.setAccessChain(partial);
1937
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001938 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1939 int dummySize;
1940 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1941 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001942 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1943 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001944 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001945 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1946 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001947 }
1948 return false;
1949 case glslang::EOpVectorSwizzle:
1950 {
1951 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001952 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001953 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001954 int dummySize;
1955 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1956 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001957 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1958 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001959 }
1960 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001961 case glslang::EOpMatrixSwizzle:
1962 logger->missingFunctionality("matrix swizzle");
1963 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001964 case glslang::EOpLogicalOr:
1965 case glslang::EOpLogicalAnd:
1966 {
1967
1968 // These may require short circuiting, but can sometimes be done as straight
1969 // binary operations. The right operand must be short circuited if it has
1970 // side effects, and should probably be if it is complex.
1971 if (isTrivial(node->getRight()->getAsTyped()))
1972 break; // handle below as a normal binary operation
1973 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001974 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1975 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001976 builder.clearAccessChain();
1977 builder.setAccessChainRValue(result);
1978 }
1979 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001980 default:
1981 break;
1982 }
1983
1984 // Assume generic binary op...
1985
John Kessenich32cfd492016-02-02 12:37:46 -07001986 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001987 builder.clearAccessChain();
1988 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001989 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001990
John Kessenich32cfd492016-02-02 12:37:46 -07001991 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001992 builder.clearAccessChain();
1993 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001994 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001995
John Kessenich32cfd492016-02-02 12:37:46 -07001996 // get result
John Kessenichead86222018-03-28 18:01:20 -06001997 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001998 TranslateNoContractionDecoration(node->getType().getQualifier()),
1999 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002000 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002001 convertGlslangToSpvType(node->getType()), left, right,
2002 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002003
John Kessenich50e57562015-12-21 21:21:11 -07002004 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002005 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002006 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002007 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002008 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002009 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002010 return false;
2011 }
John Kessenich140f3df2015-06-26 16:58:36 -06002012}
2013
John Kessenich9c14f772019-06-17 08:38:35 -06002014// Figure out what, if any, type changes are needed when accessing a specific built-in.
2015// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2016// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
2017std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
2018 const glslang::TType& glslangType)
2019{
2020 switch(builtIn)
2021 {
2022 case spv::BuiltInSubgroupEqMask:
2023 case spv::BuiltInSubgroupGeMask:
2024 case spv::BuiltInSubgroupGtMask:
2025 case spv::BuiltInSubgroupLeMask:
2026 case spv::BuiltInSubgroupLtMask: {
2027 // these require changing a 64-bit scaler -> a vector of 32-bit components
2028 if (glslangType.isVector())
2029 break;
2030 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2031 builder.makeUintType(64));
2032 return ret;
2033 }
2034 default:
2035 break;
2036 }
2037
2038 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2039 return ret;
2040}
2041
2042// For an object previously identified (see getForcedType() and forceType)
2043// as needing type translations, do the translation needed for a load, turning
2044// an L-value into in R-value.
2045spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2046{
2047 const auto forceIt = forceType.find(object);
2048 if (forceIt == forceType.end())
2049 return object;
2050
2051 spv::Id desiredTypeId = forceIt->second;
2052 spv::Id objectTypeId = builder.getTypeId(object);
2053 assert(builder.isPointerType(objectTypeId));
2054 objectTypeId = builder.getContainedTypeId(objectTypeId);
2055 if (builder.isVectorType(objectTypeId) &&
2056 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2057 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2058 // handle 32-bit v.xy* -> 64-bit
2059 builder.clearAccessChain();
2060 builder.setAccessChainLValue(object);
2061 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2062 std::vector<spv::Id> components;
2063 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2064 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2065
2066 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2067 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2068 builder.createCompositeConstruct(vecType, components));
2069 } else {
2070 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2071 }
2072 } else {
2073 logger->missingFunctionality("forcing non 32-bit vector type");
2074 }
2075
2076 return object;
2077}
2078
John Kessenich140f3df2015-06-26 16:58:36 -06002079bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2080{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002081 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002082
qining40887662016-04-03 22:20:42 -04002083 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2084 if (node->getType().getQualifier().isSpecConstant())
2085 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2086
John Kessenichfc51d282015-08-19 13:34:18 -06002087 spv::Id result = spv::NoResult;
2088
2089 // try texturing first
2090 result = createImageTextureFunctionCall(node);
2091 if (result != spv::NoResult) {
2092 builder.clearAccessChain();
2093 builder.setAccessChainRValue(result);
2094
2095 return false; // done with this node
2096 }
2097
2098 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002099
2100 if (node->getOp() == glslang::EOpArrayLength) {
2101 // Quite special; won't want to evaluate the operand.
2102
John Kessenich5611c6d2018-04-05 11:25:02 -06002103 // Currently, the front-end does not allow .length() on an array until it is sized,
2104 // except for the last block membeor of an SSBO.
2105 // TODO: If this changes, link-time sized arrays might show up here, and need their
2106 // size extracted.
2107
John Kessenichc9a80832015-09-12 12:17:44 -06002108 // Normal .length() would have been constant folded by the front-end.
2109 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002110 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002111
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002112 spv::Id length;
2113 if (node->getOperand()->getType().isCoopMat()) {
2114 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2115
2116 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2117 assert(builder.isCooperativeMatrixType(typeId));
2118
2119 length = builder.createCooperativeMatrixLength(typeId);
2120 } else {
2121 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2122 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002123 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2124 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002125 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2126 }
John Kessenichc9a80832015-09-12 12:17:44 -06002127
John Kessenich8c869672018-11-28 07:01:37 -07002128 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2129 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2130 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002131 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2132 if (builder.isInSpecConstCodeGenMode()) {
2133 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2134 } else {
2135 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2136 }
2137 }
John Kessenich8c869672018-11-28 07:01:37 -07002138
John Kessenichc9a80832015-09-12 12:17:44 -06002139 builder.clearAccessChain();
2140 builder.setAccessChainRValue(length);
2141
2142 return false;
2143 }
2144
John Kessenichfc51d282015-08-19 13:34:18 -06002145 // Start by evaluating the operand
2146
John Kessenich8c8505c2016-07-26 12:50:38 -06002147 // Does it need a swizzle inversion? If so, evaluation is inverted;
2148 // operate first on the swizzle base, then apply the swizzle.
2149 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002150 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2151 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002152 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2153 invertedType = getInvertedSwizzleType(*node->getOperand());
2154
John Kessenich140f3df2015-06-26 16:58:36 -06002155 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002156 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002157 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002158 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002159 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002160 operandNode = node->getOperand();
2161
2162 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002163
Rex Xufc618912015-09-09 16:42:49 +08002164 spv::Id operand = spv::NoResult;
2165
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002166 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2167
John Kessenichfb4f2332019-08-09 03:49:15 -06002168#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002169 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2170 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002171 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002172 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002173 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002174 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2175 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2176 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002177#endif
2178 {
John Kessenich32cfd492016-02-02 12:37:46 -07002179 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002180 }
John Kessenich140f3df2015-06-26 16:58:36 -06002181
John Kessenichead86222018-03-28 18:01:20 -06002182 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002183 TranslateNoContractionDecoration(node->getType().getQualifier()),
2184 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002185
2186 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002187 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002188 result = createConversion(node->getOp(), decorations, resultType(), operand,
2189 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002190
2191 // if not, then possibly an operation
2192 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002193 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2194 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002195
2196 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002197 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002198 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002199 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002200 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002201
John Kessenich140f3df2015-06-26 16:58:36 -06002202 builder.clearAccessChain();
2203 builder.setAccessChainRValue(result);
2204
2205 return false; // done with this node
2206 }
2207
2208 // it must be a special case, check...
2209 switch (node->getOp()) {
2210 case glslang::EOpPostIncrement:
2211 case glslang::EOpPostDecrement:
2212 case glslang::EOpPreIncrement:
2213 case glslang::EOpPreDecrement:
2214 {
2215 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002216 spv::Id one = 0;
2217 if (node->getBasicType() == glslang::EbtFloat)
2218 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002219#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002220 else if (node->getBasicType() == glslang::EbtDouble)
2221 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002222 else if (node->getBasicType() == glslang::EbtFloat16)
2223 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002224 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2225 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002226 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2227 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002228 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2229 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002230#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002231 else
2232 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002233 glslang::TOperator op;
2234 if (node->getOp() == glslang::EOpPreIncrement ||
2235 node->getOp() == glslang::EOpPostIncrement)
2236 op = glslang::EOpAdd;
2237 else
2238 op = glslang::EOpSub;
2239
John Kessenichead86222018-03-28 18:01:20 -06002240 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002241 convertGlslangToSpvType(node->getType()), operand, one,
2242 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002243 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002244
2245 // The result of operation is always stored, but conditionally the
2246 // consumed result. The consumed result is always an r-value.
2247 builder.accessChainStore(result);
2248 builder.clearAccessChain();
2249 if (node->getOp() == glslang::EOpPreIncrement ||
2250 node->getOp() == glslang::EOpPreDecrement)
2251 builder.setAccessChainRValue(result);
2252 else
2253 builder.setAccessChainRValue(operand);
2254 }
2255
2256 return false;
2257
John Kessenich155d3512019-08-08 23:29:20 -06002258#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002259 case glslang::EOpEmitStreamVertex:
2260 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2261 return false;
2262 case glslang::EOpEndStreamPrimitive:
2263 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2264 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002265#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002266
2267 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002268 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002269 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002270 }
John Kessenich140f3df2015-06-26 16:58:36 -06002271}
2272
Jeff Bolz53134492019-06-25 13:31:10 -05002273// Construct a composite object, recursively copying members if their types don't match
2274spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2275{
2276 for (int c = 0; c < (int)constituents.size(); ++c) {
2277 spv::Id& constituent = constituents[c];
2278 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2279 spv::Id rType = builder.getTypeId(constituent);
2280 if (lType != rType) {
2281 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2282 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2283 } else if (builder.isStructType(rType)) {
2284 std::vector<spv::Id> rTypeConstituents;
2285 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2286 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002287 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2288 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002289 }
2290 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2291 } else {
2292 assert(builder.isArrayType(rType));
2293 std::vector<spv::Id> rTypeConstituents;
2294 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2295
2296 spv::Id elementRType = builder.getContainedTypeId(rType);
2297 for (int i = 0; i < numrTypeConstituents; ++i) {
2298 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2299 }
2300 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2301 }
2302 }
2303 }
2304 return builder.createCompositeConstruct(resultTypeId, constituents);
2305}
2306
John Kessenich140f3df2015-06-26 16:58:36 -06002307bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2308{
qining27e04a02016-04-14 16:40:20 -04002309 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2310 if (node->getType().getQualifier().isSpecConstant())
2311 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2312
John Kessenichfc51d282015-08-19 13:34:18 -06002313 spv::Id result = spv::NoResult;
John Kessenichbbbd9a22020-03-03 07:21:37 -07002314 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
John Kessenich8985fc92020-03-03 10:25:07 -07002315 spv::Builder::AccessChain complexLvalue; // for holding swizzling l-values too complex for SPIR-V,
2316 // for at out parameter
John Kessenichbbbd9a22020-03-03 07:21:37 -07002317 spv::Id temporaryLvalue = spv::NoResult; // temporary to pass, as proxy for complexLValue
2318
John Kessenich8985fc92020-03-03 10:25:07 -07002319 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2320 invertedType :
2321 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002322
2323 // try texturing
2324 result = createImageTextureFunctionCall(node);
2325 if (result != spv::NoResult) {
2326 builder.clearAccessChain();
2327 builder.setAccessChainRValue(result);
2328
2329 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002330 }
2331#ifndef GLSLANG_WEB
2332 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002333 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002334 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002335 // "imageStore" is a special case, which has no result
2336 return false;
2337 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002338#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002339
John Kessenich140f3df2015-06-26 16:58:36 -06002340 glslang::TOperator binOp = glslang::EOpNull;
2341 bool reduceComparison = true;
2342 bool isMatrix = false;
2343 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002344 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002345
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002346 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2347
John Kessenich140f3df2015-06-26 16:58:36 -06002348 assert(node->getOp());
2349
John Kessenichf6640762016-08-01 19:44:00 -06002350 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002351
2352 switch (node->getOp()) {
2353 case glslang::EOpSequence:
2354 {
2355 if (preVisit)
2356 ++sequenceDepth;
2357 else
2358 --sequenceDepth;
2359
2360 if (sequenceDepth == 1) {
2361 // If this is the parent node of all the functions, we want to see them
2362 // early, so all call points have actual SPIR-V functions to reference.
2363 // In all cases, still let the traverser visit the children for us.
2364 makeFunctions(node->getAsAggregate()->getSequence());
2365
John Kessenich6fccb3c2016-09-19 16:01:41 -06002366 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002367 // anything else gets there, so visit out of order, doing them all now.
2368 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2369
John Kessenich6a60c2f2016-12-08 21:01:59 -07002370 // 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 -06002371 // so do them manually.
2372 visitFunctions(node->getAsAggregate()->getSequence());
2373
2374 return false;
2375 }
2376
2377 return true;
2378 }
2379 case glslang::EOpLinkerObjects:
2380 {
2381 if (visit == glslang::EvPreVisit)
2382 linkageOnly = true;
2383 else
2384 linkageOnly = false;
2385
2386 return true;
2387 }
2388 case glslang::EOpComma:
2389 {
2390 // processing from left to right naturally leaves the right-most
2391 // lying around in the access chain
2392 glslang::TIntermSequence& glslangOperands = node->getSequence();
2393 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2394 glslangOperands[i]->traverse(this);
2395
2396 return false;
2397 }
2398 case glslang::EOpFunction:
2399 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002400 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002401 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002402 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002403 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002404 } else {
2405 handleFunctionEntry(node);
2406 }
2407 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002408 if (inEntryPoint)
2409 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002410 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002411 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002412 }
2413
2414 return true;
2415 case glslang::EOpParameters:
2416 // Parameters will have been consumed by EOpFunction processing, but not
2417 // the body, so we still visited the function node's children, making this
2418 // child redundant.
2419 return false;
2420 case glslang::EOpFunctionCall:
2421 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002422 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002423 if (node->isUserDefined())
2424 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002425 if (result) {
2426 builder.clearAccessChain();
2427 builder.setAccessChainRValue(result);
2428 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002429 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002430
2431 return false;
2432 }
2433 case glslang::EOpConstructMat2x2:
2434 case glslang::EOpConstructMat2x3:
2435 case glslang::EOpConstructMat2x4:
2436 case glslang::EOpConstructMat3x2:
2437 case glslang::EOpConstructMat3x3:
2438 case glslang::EOpConstructMat3x4:
2439 case glslang::EOpConstructMat4x2:
2440 case glslang::EOpConstructMat4x3:
2441 case glslang::EOpConstructMat4x4:
2442 case glslang::EOpConstructDMat2x2:
2443 case glslang::EOpConstructDMat2x3:
2444 case glslang::EOpConstructDMat2x4:
2445 case glslang::EOpConstructDMat3x2:
2446 case glslang::EOpConstructDMat3x3:
2447 case glslang::EOpConstructDMat3x4:
2448 case glslang::EOpConstructDMat4x2:
2449 case glslang::EOpConstructDMat4x3:
2450 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002451 case glslang::EOpConstructIMat2x2:
2452 case glslang::EOpConstructIMat2x3:
2453 case glslang::EOpConstructIMat2x4:
2454 case glslang::EOpConstructIMat3x2:
2455 case glslang::EOpConstructIMat3x3:
2456 case glslang::EOpConstructIMat3x4:
2457 case glslang::EOpConstructIMat4x2:
2458 case glslang::EOpConstructIMat4x3:
2459 case glslang::EOpConstructIMat4x4:
2460 case glslang::EOpConstructUMat2x2:
2461 case glslang::EOpConstructUMat2x3:
2462 case glslang::EOpConstructUMat2x4:
2463 case glslang::EOpConstructUMat3x2:
2464 case glslang::EOpConstructUMat3x3:
2465 case glslang::EOpConstructUMat3x4:
2466 case glslang::EOpConstructUMat4x2:
2467 case glslang::EOpConstructUMat4x3:
2468 case glslang::EOpConstructUMat4x4:
2469 case glslang::EOpConstructBMat2x2:
2470 case glslang::EOpConstructBMat2x3:
2471 case glslang::EOpConstructBMat2x4:
2472 case glslang::EOpConstructBMat3x2:
2473 case glslang::EOpConstructBMat3x3:
2474 case glslang::EOpConstructBMat3x4:
2475 case glslang::EOpConstructBMat4x2:
2476 case glslang::EOpConstructBMat4x3:
2477 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002478 case glslang::EOpConstructF16Mat2x2:
2479 case glslang::EOpConstructF16Mat2x3:
2480 case glslang::EOpConstructF16Mat2x4:
2481 case glslang::EOpConstructF16Mat3x2:
2482 case glslang::EOpConstructF16Mat3x3:
2483 case glslang::EOpConstructF16Mat3x4:
2484 case glslang::EOpConstructF16Mat4x2:
2485 case glslang::EOpConstructF16Mat4x3:
2486 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002487 isMatrix = true;
2488 // fall through
2489 case glslang::EOpConstructFloat:
2490 case glslang::EOpConstructVec2:
2491 case glslang::EOpConstructVec3:
2492 case glslang::EOpConstructVec4:
2493 case glslang::EOpConstructDouble:
2494 case glslang::EOpConstructDVec2:
2495 case glslang::EOpConstructDVec3:
2496 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002497 case glslang::EOpConstructFloat16:
2498 case glslang::EOpConstructF16Vec2:
2499 case glslang::EOpConstructF16Vec3:
2500 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002501 case glslang::EOpConstructBool:
2502 case glslang::EOpConstructBVec2:
2503 case glslang::EOpConstructBVec3:
2504 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002505 case glslang::EOpConstructInt8:
2506 case glslang::EOpConstructI8Vec2:
2507 case glslang::EOpConstructI8Vec3:
2508 case glslang::EOpConstructI8Vec4:
2509 case glslang::EOpConstructUint8:
2510 case glslang::EOpConstructU8Vec2:
2511 case glslang::EOpConstructU8Vec3:
2512 case glslang::EOpConstructU8Vec4:
2513 case glslang::EOpConstructInt16:
2514 case glslang::EOpConstructI16Vec2:
2515 case glslang::EOpConstructI16Vec3:
2516 case glslang::EOpConstructI16Vec4:
2517 case glslang::EOpConstructUint16:
2518 case glslang::EOpConstructU16Vec2:
2519 case glslang::EOpConstructU16Vec3:
2520 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002521 case glslang::EOpConstructInt:
2522 case glslang::EOpConstructIVec2:
2523 case glslang::EOpConstructIVec3:
2524 case glslang::EOpConstructIVec4:
2525 case glslang::EOpConstructUint:
2526 case glslang::EOpConstructUVec2:
2527 case glslang::EOpConstructUVec3:
2528 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002529 case glslang::EOpConstructInt64:
2530 case glslang::EOpConstructI64Vec2:
2531 case glslang::EOpConstructI64Vec3:
2532 case glslang::EOpConstructI64Vec4:
2533 case glslang::EOpConstructUint64:
2534 case glslang::EOpConstructU64Vec2:
2535 case glslang::EOpConstructU64Vec3:
2536 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002537 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002538 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002539 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002540 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002541 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002542 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002543 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002544 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002545 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002546 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002547 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002548 else if (node->getOp() == glslang::EOpConstructStruct ||
2549 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2550 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002551 std::vector<spv::Id> constituents;
2552 for (int c = 0; c < (int)arguments.size(); ++c)
2553 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002554 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002555 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002556 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002557 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002558 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002559
2560 builder.clearAccessChain();
2561 builder.setAccessChainRValue(constructed);
2562
2563 return false;
2564 }
2565
2566 // These six are component-wise compares with component-wise results.
2567 // Forward on to createBinaryOperation(), requesting a vector result.
2568 case glslang::EOpLessThan:
2569 case glslang::EOpGreaterThan:
2570 case glslang::EOpLessThanEqual:
2571 case glslang::EOpGreaterThanEqual:
2572 case glslang::EOpVectorEqual:
2573 case glslang::EOpVectorNotEqual:
2574 {
2575 // Map the operation to a binary
2576 binOp = node->getOp();
2577 reduceComparison = false;
2578 switch (node->getOp()) {
2579 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2580 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2581 default: binOp = node->getOp(); break;
2582 }
2583
2584 break;
2585 }
2586 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002587 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002588 binOp = glslang::EOpMul;
2589 break;
2590 case glslang::EOpOuterProduct:
2591 // two vectors multiplied to make a matrix
2592 binOp = glslang::EOpOuterProduct;
2593 break;
2594 case glslang::EOpDot:
2595 {
qining25262b32016-05-06 17:25:16 -04002596 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002597 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002598 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002599 binOp = glslang::EOpMul;
2600 break;
2601 }
2602 case glslang::EOpMod:
2603 // when an aggregate, this is the floating-point mod built-in function,
2604 // which can be emitted by the one in createBinaryOperation()
2605 binOp = glslang::EOpMod;
2606 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002607
John Kessenich140f3df2015-06-26 16:58:36 -06002608 case glslang::EOpEmitVertex:
2609 case glslang::EOpEndPrimitive:
2610 case glslang::EOpBarrier:
2611 case glslang::EOpMemoryBarrier:
2612 case glslang::EOpMemoryBarrierAtomicCounter:
2613 case glslang::EOpMemoryBarrierBuffer:
2614 case glslang::EOpMemoryBarrierImage:
2615 case glslang::EOpMemoryBarrierShared:
2616 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002617 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002618 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002619 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002620 case glslang::EOpWorkgroupMemoryBarrier:
2621 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002622 case glslang::EOpSubgroupBarrier:
2623 case glslang::EOpSubgroupMemoryBarrier:
2624 case glslang::EOpSubgroupMemoryBarrierBuffer:
2625 case glslang::EOpSubgroupMemoryBarrierImage:
2626 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002627 noReturnValue = true;
2628 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2629 break;
2630
John Kessenich426394d2015-07-23 10:22:48 -06002631 case glslang::EOpAtomicAdd:
2632 case glslang::EOpAtomicMin:
2633 case glslang::EOpAtomicMax:
2634 case glslang::EOpAtomicAnd:
2635 case glslang::EOpAtomicOr:
2636 case glslang::EOpAtomicXor:
2637 case glslang::EOpAtomicExchange:
2638 case glslang::EOpAtomicCompSwap:
2639 atomic = true;
2640 break;
2641
John Kesseniche5eee8f2019-10-18 01:03:11 -06002642#ifndef GLSLANG_WEB
2643 case glslang::EOpAtomicStore:
2644 noReturnValue = true;
2645 // fallthrough
2646 case glslang::EOpAtomicLoad:
2647 atomic = true;
2648 break;
2649
John Kessenich0d0c6d32017-07-23 16:08:26 -06002650 case glslang::EOpAtomicCounterAdd:
2651 case glslang::EOpAtomicCounterSubtract:
2652 case glslang::EOpAtomicCounterMin:
2653 case glslang::EOpAtomicCounterMax:
2654 case glslang::EOpAtomicCounterAnd:
2655 case glslang::EOpAtomicCounterOr:
2656 case glslang::EOpAtomicCounterXor:
2657 case glslang::EOpAtomicCounterExchange:
2658 case glslang::EOpAtomicCounterCompSwap:
2659 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2660 builder.addCapability(spv::CapabilityAtomicStorageOps);
2661 atomic = true;
2662 break;
2663
Ian Romanickb3bd4022019-01-21 08:57:25 -08002664 case glslang::EOpAbsDifference:
2665 case glslang::EOpAddSaturate:
2666 case glslang::EOpSubSaturate:
2667 case glslang::EOpAverage:
2668 case glslang::EOpAverageRounded:
2669 case glslang::EOpMul32x16:
2670 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2671 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2672 binOp = node->getOp();
2673 break;
2674
Chao Chenb50c02e2018-09-19 11:42:24 -07002675 case glslang::EOpIgnoreIntersectionNV:
2676 case glslang::EOpTerminateRayNV:
2677 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002678 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002679 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2680 noReturnValue = true;
2681 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002682 case glslang::EOpCooperativeMatrixLoad:
2683 case glslang::EOpCooperativeMatrixStore:
2684 noReturnValue = true;
2685 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002686 case glslang::EOpBeginInvocationInterlock:
2687 case glslang::EOpEndInvocationInterlock:
2688 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2689 noReturnValue = true;
2690 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002691#endif
Chao Chen3c366992018-09-19 11:41:59 -07002692
Jeff Bolz04d73732019-05-31 13:06:01 -05002693 case glslang::EOpDebugPrintf:
2694 noReturnValue = true;
2695 break;
2696
John Kessenich140f3df2015-06-26 16:58:36 -06002697 default:
2698 break;
2699 }
2700
2701 //
2702 // See if it maps to a regular operation.
2703 //
John Kessenich140f3df2015-06-26 16:58:36 -06002704 if (binOp != glslang::EOpNull) {
2705 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2706 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2707 assert(left && right);
2708
2709 builder.clearAccessChain();
2710 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002711 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002712
2713 builder.clearAccessChain();
2714 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002715 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002716
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002717 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002718 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002719 TranslateNoContractionDecoration(node->getType().getQualifier()),
2720 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002721 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002722 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002723 left->getType().getBasicType(), reduceComparison);
2724
2725 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002726 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002727 builder.clearAccessChain();
2728 builder.setAccessChainRValue(result);
2729
2730 return false;
2731 }
2732
John Kessenich426394d2015-07-23 10:22:48 -06002733 //
2734 // Create the list of operands.
2735 //
John Kessenich140f3df2015-06-26 16:58:36 -06002736 glslang::TIntermSequence& glslangOperands = node->getSequence();
2737 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002738 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002739 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002740 // special case l-value operands; there are just a few
2741 bool lvalue = false;
2742 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002743 case glslang::EOpModf:
2744 if (arg == 1)
2745 lvalue = true;
2746 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002747
2748 case glslang::EOpAtomicAdd:
2749 case glslang::EOpAtomicMin:
2750 case glslang::EOpAtomicMax:
2751 case glslang::EOpAtomicAnd:
2752 case glslang::EOpAtomicOr:
2753 case glslang::EOpAtomicXor:
2754 case glslang::EOpAtomicExchange:
2755 case glslang::EOpAtomicCompSwap:
2756 if (arg == 0)
2757 lvalue = true;
2758 break;
2759
John Kessenicha28f7a72019-08-06 07:00:58 -06002760#ifndef GLSLANG_WEB
2761 case glslang::EOpFrexp:
2762 if (arg == 1)
2763 lvalue = true;
2764 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002765 case glslang::EOpInterpolateAtSample:
2766 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002767 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002768 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002769 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002770
2771 // Does it need a swizzle inversion? If so, evaluation is inverted;
2772 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002773 // That is, we transform
2774 //
2775 // interpolate(v.zy) -> interpolate(v).zy
2776 //
John Kessenichecba76f2017-01-06 00:34:48 -07002777 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002778 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002779 invertedType = convertGlslangToSpvType(
2780 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002781 }
Rex Xu7a26c172015-12-08 17:12:09 +08002782 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002783 case glslang::EOpAtomicLoad:
2784 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002785 case glslang::EOpAtomicCounterAdd:
2786 case glslang::EOpAtomicCounterSubtract:
2787 case glslang::EOpAtomicCounterMin:
2788 case glslang::EOpAtomicCounterMax:
2789 case glslang::EOpAtomicCounterAnd:
2790 case glslang::EOpAtomicCounterOr:
2791 case glslang::EOpAtomicCounterXor:
2792 case glslang::EOpAtomicCounterExchange:
2793 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002794 if (arg == 0)
2795 lvalue = true;
2796 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002797 case glslang::EOpAddCarry:
2798 case glslang::EOpSubBorrow:
2799 if (arg == 2)
2800 lvalue = true;
2801 break;
2802 case glslang::EOpUMulExtended:
2803 case glslang::EOpIMulExtended:
2804 if (arg >= 2)
2805 lvalue = true;
2806 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002807 case glslang::EOpCooperativeMatrixLoad:
2808 if (arg == 0 || arg == 1)
2809 lvalue = true;
2810 break;
2811 case glslang::EOpCooperativeMatrixStore:
2812 if (arg == 1)
2813 lvalue = true;
2814 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002815#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002816 default:
2817 break;
2818 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002819 builder.clearAccessChain();
2820 if (invertedType != spv::NoType && arg == 0)
2821 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2822 else
2823 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002824
John Kessenichb9197c82019-08-11 07:41:45 -06002825#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002826 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2827 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2828
2829 if (arg == 1) {
2830 // fold "element" parameter into the access chain
2831 spv::Builder::AccessChain save = builder.getAccessChain();
2832 builder.clearAccessChain();
2833 glslangOperands[2]->traverse(this);
2834
2835 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2836
2837 builder.setAccessChain(save);
2838
2839 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002840 builder.accessChainPush(elementId,
2841 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2842 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002843
2844 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2845 unsigned int alignment = builder.getAccessChain().alignment;
2846
2847 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2848 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2849 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2850 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2851 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002852 if (builder.getStorageClass(builder.getAccessChain().base) ==
2853 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002854 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2855 }
2856
2857 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2858
2859 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2860 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2861 }
2862
John Kessenich8985fc92020-03-03 10:25:07 -07002863 if (memoryAccess &
2864 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2865 memoryAccessOperands.push_back(spv::IdImmediate(true,
2866 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002867 }
2868 } else if (arg == 2) {
2869 continue;
2870 }
2871 }
John Kessenichb9197c82019-08-11 07:41:45 -06002872#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002873
John Kessenichbbbd9a22020-03-03 07:21:37 -07002874 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002875 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002876 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2877 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2878 // reduce to a simple access chain. So, we need a temporary vector to
2879 // receive the result, and must later swizzle that into the original
2880 // l-value.
2881 complexLvalue = builder.getAccessChain();
John Kessenich8985fc92020-03-03 10:25:07 -07002882 temporaryLvalue = builder.createVariable(spv::StorageClassFunction,
2883 builder.accessChainGetInferredType(), "swizzleTemp");
John Kessenichbbbd9a22020-03-03 07:21:37 -07002884 operands.push_back(temporaryLvalue);
2885 } else {
2886 operands.push_back(builder.accessChainGetLValue());
2887 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002888 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2889 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2890 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002891 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002892 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002893 }
John Kessenich140f3df2015-06-26 16:58:36 -06002894 }
John Kessenich426394d2015-07-23 10:22:48 -06002895
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002896 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002897#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002898 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2899 std::vector<spv::IdImmediate> idImmOps;
2900
2901 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2902 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2903 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2904 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2905 // get the pointee type
2906 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2907 assert(builder.isCooperativeMatrixType(typeId));
2908 // do the op
2909 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2910 // store the result to the pointer (out param 'm')
2911 builder.createStore(result, operands[0]);
2912 result = 0;
2913 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2914 std::vector<spv::IdImmediate> idImmOps;
2915
2916 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2917 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2918 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2919 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2920 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2921
2922 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2923 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06002924 } else
2925#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06002926 if (atomic) {
2927 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07002928 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
2929 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05002930 } else if (node->getOp() == glslang::EOpDebugPrintf) {
2931 if (!nonSemanticDebugPrintf) {
2932 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
2933 }
2934 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
2935 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06002936 } else {
John Kessenich426394d2015-07-23 10:22:48 -06002937 // Pass through to generic operations.
2938 switch (glslangOperands.size()) {
2939 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002940 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002941 break;
2942 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002943 {
2944 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002945 TranslateNoContractionDecoration(node->getType().getQualifier()),
2946 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002947 result = createUnaryOperation(
2948 node->getOp(), decorations,
2949 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002950 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002951 }
John Kessenich426394d2015-07-23 10:22:48 -06002952 break;
2953 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002954 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002955 break;
2956 }
John Kessenichbbbd9a22020-03-03 07:21:37 -07002957 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06002958 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenichbbbd9a22020-03-03 07:21:37 -07002959 else if (temporaryLvalue != spv::NoResult) {
2960 builder.setAccessChain(complexLvalue);
2961 builder.accessChainStore(builder.createLoad(temporaryLvalue));
2962 }
John Kessenich140f3df2015-06-26 16:58:36 -06002963 }
2964
2965 if (noReturnValue)
2966 return false;
2967
2968 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002969 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002970 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002971 } else {
2972 builder.clearAccessChain();
2973 builder.setAccessChainRValue(result);
2974 return false;
2975 }
2976}
2977
John Kessenich433e9ff2017-01-26 20:31:11 -07002978// This path handles both if-then-else and ?:
2979// The if-then-else has a node type of void, while
2980// ?: has either a void or a non-void node type
2981//
2982// Leaving the result, when not void:
2983// GLSL only has r-values as the result of a :?, but
2984// if we have an l-value, that can be more efficient if it will
2985// become the base of a complex r-value expression, because the
2986// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002987bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2988{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002989 // see if OpSelect can handle it
2990 const auto isOpSelectable = [&]() {
2991 if (node->getBasicType() == glslang::EbtVoid)
2992 return false;
2993 // OpSelect can do all other types starting with SPV 1.4
2994 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2995 // pre-1.4, only scalars and vectors can be handled
2996 if ((!node->getType().isScalar() && !node->getType().isVector()))
2997 return false;
2998 }
2999 return true;
3000 };
3001
John Kessenich4bee5312018-02-20 21:29:05 -07003002 // See if it simple and safe, or required, to execute both sides.
3003 // Crucially, side effects must be either semantically required or avoided,
3004 // and there are performance trade-offs.
3005 // Return true if required or a good idea (and safe) to execute both sides,
3006 // false otherwise.
3007 const auto bothSidesPolicy = [&]() -> bool {
3008 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003009 if (node->getTrueBlock() == nullptr ||
3010 node->getFalseBlock() == nullptr)
3011 return false;
3012
John Kessenich4bee5312018-02-20 21:29:05 -07003013 // required? (unless we write additional code to look for side effects
3014 // and make performance trade-offs if none are present)
3015 if (!node->getShortCircuit())
3016 return true;
3017
3018 // if not required to execute both, decide based on performance/practicality...
3019
John Kessenich0c1e71a2019-01-10 18:23:06 +07003020 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003021 return false;
3022
John Kessenich433e9ff2017-01-26 20:31:11 -07003023 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3024 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3025
3026 // return true if a single operand to ? : is okay for OpSelect
3027 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003028 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003029 };
3030
3031 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3032 operandOkay(node->getFalseBlock()->getAsTyped());
3033 };
3034
John Kessenich4bee5312018-02-20 21:29:05 -07003035 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3036 // emit the condition before doing anything with selection
3037 node->getCondition()->traverse(this);
3038 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3039
3040 // Find a way of executing both sides and selecting the right result.
3041 const auto executeBothSides = [&]() -> void {
3042 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003043 node->getTrueBlock()->traverse(this);
3044 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3045 node->getFalseBlock()->traverse(this);
3046 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3047
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003048 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003049
John Kessenich4bee5312018-02-20 21:29:05 -07003050 // done if void
3051 if (node->getBasicType() == glslang::EbtVoid)
3052 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003053
John Kessenich4bee5312018-02-20 21:29:05 -07003054 // emit code to select between trueValue and falseValue
3055
3056 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003057 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003058 // Emit OpSelect for this selection.
3059
3060 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003061 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3062 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003063 condition = builder.smearScalar(spv::NoPrecision, condition,
3064 builder.makeVectorType(builder.makeBoolType(),
3065 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003066 }
John Kessenich4bee5312018-02-20 21:29:05 -07003067
3068 // OpSelect
3069 result = builder.createTriOp(spv::OpSelect,
3070 convertGlslangToSpvType(node->getType()), condition,
3071 trueValue, falseValue);
3072
3073 builder.clearAccessChain();
3074 builder.setAccessChainRValue(result);
3075 } else {
3076 // We need control flow to select the result.
3077 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3078 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3079
3080 // Selection control:
3081 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3082
3083 // make an "if" based on the value created by the condition
3084 spv::Builder::If ifBuilder(condition, control, builder);
3085
3086 // emit the "then" statement
3087 builder.createStore(trueValue, result);
3088 ifBuilder.makeBeginElse();
3089 // emit the "else" statement
3090 builder.createStore(falseValue, result);
3091
3092 // finish off the control flow
3093 ifBuilder.makeEndIf();
3094
3095 builder.clearAccessChain();
3096 builder.setAccessChainLValue(result);
3097 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003098 };
3099
John Kessenich4bee5312018-02-20 21:29:05 -07003100 // Execute the one side needed, as per the condition
3101 const auto executeOneSide = [&]() {
3102 // Always emit control flow.
3103 if (node->getBasicType() != glslang::EbtVoid)
3104 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003105
John Kessenich4bee5312018-02-20 21:29:05 -07003106 // Selection control:
3107 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3108
3109 // make an "if" based on the value created by the condition
3110 spv::Builder::If ifBuilder(condition, control, builder);
3111
3112 // emit the "then" statement
3113 if (node->getTrueBlock() != nullptr) {
3114 node->getTrueBlock()->traverse(this);
3115 if (result != spv::NoResult)
3116 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3117 }
3118
3119 if (node->getFalseBlock() != nullptr) {
3120 ifBuilder.makeBeginElse();
3121 // emit the "else" statement
3122 node->getFalseBlock()->traverse(this);
3123 if (result != spv::NoResult)
3124 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3125 }
3126
3127 // finish off the control flow
3128 ifBuilder.makeEndIf();
3129
3130 if (result != spv::NoResult) {
3131 builder.clearAccessChain();
3132 builder.setAccessChainLValue(result);
3133 }
3134 };
3135
3136 // Try for OpSelect (or a requirement to execute both sides)
3137 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003138 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3139 if (node->getType().getQualifier().isSpecConstant())
3140 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003141 executeBothSides();
3142 } else
3143 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003144
3145 return false;
3146}
3147
3148bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3149{
3150 // emit and get the condition before doing anything with switch
3151 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003152 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003153
Rex Xu57e65922017-07-04 23:23:40 +08003154 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003155 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003156
John Kessenich140f3df2015-06-26 16:58:36 -06003157 // browse the children to sort out code segments
3158 int defaultSegment = -1;
3159 std::vector<TIntermNode*> codeSegments;
3160 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3161 std::vector<int> caseValues;
3162 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3163 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3164 TIntermNode* child = *c;
3165 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003166 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003167 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003168 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003169 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3170 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003171 } else
3172 codeSegments.push_back(child);
3173 }
3174
qining25262b32016-05-06 17:25:16 -04003175 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003176 // statements between the last case and the end of the switch statement
3177 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3178 (int)codeSegments.size() == defaultSegment)
3179 codeSegments.push_back(nullptr);
3180
3181 // make the switch statement
3182 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003183 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3184 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003185
3186 // emit all the code in the segments
3187 breakForLoop.push(false);
3188 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3189 builder.nextSwitchSegment(segmentBlocks, s);
3190 if (codeSegments[s])
3191 codeSegments[s]->traverse(this);
3192 else
3193 builder.addSwitchBreak();
3194 }
3195 breakForLoop.pop();
3196
3197 builder.endSwitch(segmentBlocks);
3198
3199 return false;
3200}
3201
3202void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3203{
3204 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003205 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003206
3207 builder.clearAccessChain();
3208 builder.setAccessChainRValue(constant);
3209}
3210
3211bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3212{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003213 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003214 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003215
3216 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003217 std::vector<unsigned int> operands;
3218 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003219
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003220 // Spec requires back edges to target header blocks, and every header block
3221 // must dominate its merge block. Make a header block first to ensure these
3222 // conditions are met. By definition, it will contain OpLoopMerge, followed
3223 // by a block-ending branch. But we don't want to put any other body/test
3224 // instructions in it, since the body/test may have arbitrary instructions,
3225 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003226 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003227 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003228 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003229 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003230 spv::Block& test = builder.makeNewBlock();
3231 builder.createBranch(&test);
3232
3233 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003234 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003235 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003236 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3237
3238 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003239 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003240 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003241 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003242 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003243 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003244
3245 builder.setBuildPoint(&blocks.continue_target);
3246 if (node->getTerminal())
3247 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003248 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003249 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003250 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003251 builder.createBranch(&blocks.body);
3252
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003253 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003254 builder.setBuildPoint(&blocks.body);
3255 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003256 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003257 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003258 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003259
3260 builder.setBuildPoint(&blocks.continue_target);
3261 if (node->getTerminal())
3262 node->getTerminal()->traverse(this);
3263 if (node->getTest()) {
3264 node->getTest()->traverse(this);
3265 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003266 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003267 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003268 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003269 // TODO: unless there was a break/return/discard instruction
3270 // somewhere in the body, this is an infinite loop, so we should
3271 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003272 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003273 }
John Kessenich140f3df2015-06-26 16:58:36 -06003274 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003275 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003276 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003277 return false;
3278}
3279
3280bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3281{
3282 if (node->getExpression())
3283 node->getExpression()->traverse(this);
3284
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003285 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003286
John Kessenich140f3df2015-06-26 16:58:36 -06003287 switch (node->getFlowOp()) {
3288 case glslang::EOpKill:
3289 builder.makeDiscard();
3290 break;
3291 case glslang::EOpBreak:
3292 if (breakForLoop.top())
3293 builder.createLoopExit();
3294 else
3295 builder.addSwitchBreak();
3296 break;
3297 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003298 builder.createLoopContinue();
3299 break;
3300 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003301 if (node->getExpression()) {
3302 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3303 spv::Id returnId = accessChainLoad(glslangReturnType);
3304 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3305 builder.clearAccessChain();
3306 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3307 builder.setAccessChainLValue(copyId);
3308 multiTypeStore(glslangReturnType, returnId);
3309 returnId = builder.createLoad(copyId);
3310 }
3311 builder.makeReturn(false, returnId);
3312 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003313 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003314
3315 builder.clearAccessChain();
3316 break;
3317
John Kessenichb9197c82019-08-11 07:41:45 -06003318#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003319 case glslang::EOpDemote:
3320 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3321 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3322 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3323 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003324#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003325
John Kessenich140f3df2015-06-26 16:58:36 -06003326 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003327 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003328 break;
3329 }
3330
3331 return false;
3332}
3333
John Kessenich9c14f772019-06-17 08:38:35 -06003334spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003335{
qining25262b32016-05-06 17:25:16 -04003336 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003337 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003338 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003339 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003340 spv::Id result = createSpvConstant(*node);
3341 if (result != spv::NoResult)
3342 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003343 }
3344
3345 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003346 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003347 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3348 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003349
John Kessenichb9197c82019-08-11 07:41:45 -06003350 const bool contains16BitType = node->getType().contains16BitFloat() ||
3351 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003352 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003353 switch (storageClass) {
3354 case spv::StorageClassInput:
3355 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003356 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003357 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003358 break;
John Kessenich18310872018-05-14 22:08:53 -06003359 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003360 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003361 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3362 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003363 else
3364 builder.addCapability(spv::CapabilityStorageUniform16);
3365 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003366#ifndef GLSLANG_WEB
3367 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003368 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003369 builder.addCapability(spv::CapabilityStoragePushConstant16);
3370 break;
John Kessenich18310872018-05-14 22:08:53 -06003371 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003372 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003373 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003374 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3375 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003376#endif
John Kessenich18310872018-05-14 22:08:53 -06003377 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003378 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003379 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003380 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003381 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003382 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003383 }
3384 }
Rex Xuf89ad982017-04-07 23:22:33 +08003385
John Kessenichb9197c82019-08-11 07:41:45 -06003386 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003387 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003388 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003389 builder.addCapability(spv::CapabilityStoragePushConstant8);
3390 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003391 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003392 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003393 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003394 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003395 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003396 } else {
3397 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003398 }
3399 }
3400
John Kessenich140f3df2015-06-26 16:58:36 -06003401 const char* name = node->getName().c_str();
3402 if (glslang::IsAnonymous(name))
3403 name = "";
3404
3405 return builder.createVariable(storageClass, spvType, name);
3406}
3407
3408// Return type Id of the sampled type.
3409spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3410{
3411 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003412 case glslang::EbtInt: return builder.makeIntType(32);
3413 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003414 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003415#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003416 case glslang::EbtFloat16:
3417 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3418 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3419 return builder.makeFloatType(16);
3420#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003421 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003422 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003423 return builder.makeFloatType(32);
3424 }
3425}
3426
John Kessenich8c8505c2016-07-26 12:50:38 -06003427// If node is a swizzle operation, return the type that should be used if
3428// the swizzle base is first consumed by another operation, before the swizzle
3429// is applied.
3430spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3431{
John Kessenichecba76f2017-01-06 00:34:48 -07003432 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003433 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3434 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3435 else
3436 return spv::NoType;
3437}
3438
3439// When inverting a swizzle with a parent op, this function
3440// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003441spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3442 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003443{
3444 std::vector<unsigned> swizzle;
3445 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3446 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3447}
3448
John Kessenich8c8505c2016-07-26 12:50:38 -06003449// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3450void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3451{
3452 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3453 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3454 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3455}
3456
John Kessenich3ac051e2015-12-20 11:29:16 -07003457// Convert from a glslang type to an SPV type, by calling into a
3458// recursive version of this function. This establishes the inherited
3459// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003460spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003461{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003462 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003463}
3464
3465// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003466// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003467// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003468spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003469 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3470 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003471{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003472 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003473
3474 switch (type.getBasicType()) {
3475 case glslang::EbtVoid:
3476 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003477 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003478 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003479 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003480 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3481 // a 32-bit int where non-0 means true.
3482 if (explicitLayout != glslang::ElpNone)
3483 spvType = builder.makeUintType(32);
3484 else
3485 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003486 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003487 case glslang::EbtInt:
3488 spvType = builder.makeIntType(32);
3489 break;
3490 case glslang::EbtUint:
3491 spvType = builder.makeUintType(32);
3492 break;
3493 case glslang::EbtFloat:
3494 spvType = builder.makeFloatType(32);
3495 break;
3496#ifndef GLSLANG_WEB
3497 case glslang::EbtDouble:
3498 spvType = builder.makeFloatType(64);
3499 break;
3500 case glslang::EbtFloat16:
3501 spvType = builder.makeFloatType(16);
3502 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003503 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003504 spvType = builder.makeIntType(8);
3505 break;
3506 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003507 spvType = builder.makeUintType(8);
3508 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003509 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003510 spvType = builder.makeIntType(16);
3511 break;
3512 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003513 spvType = builder.makeUintType(16);
3514 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003515 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003516 spvType = builder.makeIntType(64);
3517 break;
3518 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003519 spvType = builder.makeUintType(64);
3520 break;
John Kessenich426394d2015-07-23 10:22:48 -06003521 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003522 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003523 spvType = builder.makeUintType(32);
3524 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003525 case glslang::EbtAccStructNV:
3526 spvType = builder.makeAccelerationStructureNVType();
3527 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003528 case glslang::EbtReference:
3529 {
3530 // Make the forward pointer, then recurse to convert the structure type, then
3531 // patch up the forward pointer with a real pointer type.
3532 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3533 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3534 forwardPointers[type.getReferentType()] = forwardId;
3535 }
3536 spvType = forwardPointers[type.getReferentType()];
3537 if (!forwardReferenceOnly) {
3538 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3539 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3540 forwardPointers[type.getReferentType()],
3541 referentType);
3542 }
3543 }
3544 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003545#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003546 case glslang::EbtSampler:
3547 {
3548 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003549 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003550 spvType = builder.makeSamplerType();
3551 } else {
3552 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003553 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3554 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3555 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3556 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003557 // already has both image and sampler, make the combined type
3558 spvType = builder.makeSampledImageType(spvType);
3559 }
John Kessenich55e7d112015-11-15 21:33:39 -07003560 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003561 }
John Kessenich140f3df2015-06-26 16:58:36 -06003562 break;
3563 case glslang::EbtStruct:
3564 case glslang::EbtBlock:
3565 {
3566 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003567 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003568
3569 // Try to share structs for different layouts, but not yet for other
3570 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003571 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003572 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003573 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003574 break;
3575
3576 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003577 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003578 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003579 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003580 }
3581 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003582 case glslang::EbtString:
3583 // no type used for OpString
3584 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003585 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003586 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003587 break;
3588 }
3589
3590 if (type.isMatrix())
3591 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3592 else {
3593 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3594 if (type.getVectorSize() > 1)
3595 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3596 }
3597
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003598 if (type.isCoopMat()) {
3599 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3600 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3601 if (type.getBasicType() == glslang::EbtFloat16)
3602 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003603 if (type.getBasicType() == glslang::EbtUint8 ||
3604 type.getBasicType() == glslang::EbtInt8) {
3605 builder.addCapability(spv::CapabilityInt8);
3606 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003607
3608 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3609 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3610 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3611
3612 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3613 }
3614
John Kessenich140f3df2015-06-26 16:58:36 -06003615 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003616 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3617
John Kessenichc9a80832015-09-12 12:17:44 -06003618 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003619 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003620 // We need to decorate array strides for types needing explicit layout, except blocks.
3621 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003622 // Use a dummy glslang type for querying internal strides of
3623 // arrays of arrays, but using just a one-dimensional array.
3624 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003625 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3626 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003627
3628 // Will compute the higher-order strides here, rather than making a whole
3629 // pile of types and doing repetitive recursion on their contents.
3630 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3631 }
John Kessenichf8842e52016-01-04 19:22:56 -07003632
3633 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003634 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003635 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003636 if (stride > 0)
3637 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003638 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003639 }
3640 } else {
3641 // single-dimensional array, and don't yet have stride
3642
John Kessenichf8842e52016-01-04 19:22:56 -07003643 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003644 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3645 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003646 }
John Kessenich31ed4832015-09-09 17:51:38 -06003647
John Kessenichead86222018-03-28 18:01:20 -06003648 // Do the outer dimension, which might not be known for a runtime-sized array.
3649 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3650 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003651 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003652 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003653#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003654 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003655 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003656 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3657 }
John Kessenichb9197c82019-08-11 07:41:45 -06003658#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003659 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003660 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003661 if (stride > 0)
3662 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003663 }
3664
3665 return spvType;
3666}
3667
John Kessenich0e737842017-03-24 18:38:16 -06003668// TODO: this functionality should exist at a higher level, in creating the AST
3669//
3670// Identify interface members that don't have their required extension turned on.
3671//
3672bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3673{
John Kessenicha28f7a72019-08-06 07:00:58 -06003674#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003675 auto& extensions = glslangIntermediate->getRequestedExtensions();
3676
Rex Xubcf291a2017-03-29 23:01:36 +08003677 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3678 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3679 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003680 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3681 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3682 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003683
3684 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3685 if (member.getFieldName() == "gl_ViewportMask" &&
3686 extensions.find("GL_NV_viewport_array2") == extensions.end())
3687 return true;
3688 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3689 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3690 return true;
3691 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3692 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3693 return true;
3694 }
3695#endif
John Kessenich0e737842017-03-24 18:38:16 -06003696
3697 return false;
3698};
3699
John Kessenich6090df02016-06-30 21:18:02 -06003700// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3701// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3702// Mutually recursive with convertGlslangToSpvType().
3703spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3704 const glslang::TTypeList* glslangMembers,
3705 glslang::TLayoutPacking explicitLayout,
3706 const glslang::TQualifier& qualifier)
3707{
3708 // Create a vector of struct types for SPIR-V to consume
3709 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003710 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3711 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003712 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003713 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3714 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3715 if (glslangMember.hiddenMember()) {
3716 ++memberDelta;
3717 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003718 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003719 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003720 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003721 if (filterMember(glslangMember)) {
3722 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003723 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003724 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003725 }
Roy05a5b532020-01-03 16:21:34 +08003726 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003727 }
John Kessenich6090df02016-06-30 21:18:02 -06003728 // modify just this child's view of the qualifier
3729 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3730 InheritQualifiers(memberQualifier, qualifier);
3731
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003732 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003733 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003734 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003735
3736 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003737 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3738 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003739
3740 // Make forward pointers for any pointer members, and create a list of members to
3741 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003742 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003743 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3744 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3745 }
3746 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003747 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3748 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003749 } else {
3750 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003751 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3752 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003753 }
John Kessenich6090df02016-06-30 21:18:02 -06003754 }
3755 }
3756
3757 // Make the SPIR-V type
3758 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003759 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003760 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3761
3762 // Decorate it
3763 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3764
John Kessenichd72f4882019-01-16 14:55:37 +07003765 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003766 auto it = deferredForwardPointers[i];
3767 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3768 }
3769
John Kessenich6090df02016-06-30 21:18:02 -06003770 return spvType;
3771}
3772
3773void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3774 const glslang::TTypeList* glslangMembers,
3775 glslang::TLayoutPacking explicitLayout,
3776 const glslang::TQualifier& qualifier,
3777 spv::Id spvType)
3778{
3779 // Name and decorate the non-hidden members
3780 int offset = -1;
3781 int locationOffset = 0; // for use within the members of this struct
3782 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3783 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3784 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003785 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003786 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003787 if (filterMember(glslangMember))
3788 continue;
3789 }
John Kessenich6090df02016-06-30 21:18:02 -06003790
3791 // modify just this child's view of the qualifier
3792 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3793 InheritQualifiers(memberQualifier, qualifier);
3794
3795 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003796 if (member < 0)
3797 continue;
3798
3799 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3800 builder.addMemberDecoration(spvType, member,
3801 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3802 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3803 // Add interpolation and auxiliary storage decorations only to
3804 // top-level members of Input and Output storage classes
3805 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3806 type.getQualifier().storage == glslang::EvqVaryingOut) {
3807 if (type.getBasicType() == glslang::EbtBlock ||
3808 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3809 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3810 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003811#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003812 addMeshNVDecoration(spvType, member, memberQualifier);
3813#endif
John Kessenich6090df02016-06-30 21:18:02 -06003814 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003815 }
3816 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003817
John Kessenichb9197c82019-08-11 07:41:45 -06003818#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003819 if (type.getBasicType() == glslang::EbtBlock &&
3820 qualifier.storage == glslang::EvqBuffer) {
3821 // Add memory decorations only to top-level members of shader storage block
3822 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003823 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003824 for (unsigned int i = 0; i < memory.size(); ++i)
3825 builder.addMemberDecoration(spvType, member, memory[i]);
3826 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003827
John Kessenichb9197c82019-08-11 07:41:45 -06003828#endif
John Kessenich6090df02016-06-30 21:18:02 -06003829
John Kessenich5d610ee2018-03-07 18:05:55 -07003830 // Location assignment was already completed correctly by the front end,
3831 // just track whether a member needs to be decorated.
3832 // Ignore member locations if the container is an array, as that's
3833 // ill-specified and decisions have been made to not allow this.
3834 if (! type.isArray() && memberQualifier.hasLocation())
3835 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003836
John Kessenich5d610ee2018-03-07 18:05:55 -07003837 if (qualifier.hasLocation()) // track for upcoming inheritance
3838 locationOffset += glslangIntermediate->computeTypeLocationSize(
3839 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003840
John Kessenich5d610ee2018-03-07 18:05:55 -07003841 // component, XFB, others
3842 if (glslangMember.getQualifier().hasComponent())
3843 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3844 glslangMember.getQualifier().layoutComponent);
3845 if (glslangMember.getQualifier().hasXfbOffset())
3846 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3847 glslangMember.getQualifier().layoutXfbOffset);
3848 else if (explicitLayout != glslang::ElpNone) {
3849 // figure out what to do with offset, which is accumulating
3850 int nextOffset;
3851 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3852 if (offset >= 0)
3853 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3854 offset = nextOffset;
3855 }
John Kessenich6090df02016-06-30 21:18:02 -06003856
John Kessenich5d610ee2018-03-07 18:05:55 -07003857 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3858 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3859 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003860
John Kessenich5d610ee2018-03-07 18:05:55 -07003861 // built-in variable decorations
3862 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3863 if (builtIn != spv::BuiltInMax)
3864 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003865
John Kessenichb9197c82019-08-11 07:41:45 -06003866#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003867 // nonuniform
3868 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3869
John Kessenichead86222018-03-28 18:01:20 -06003870 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3871 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3872 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3873 memberQualifier.semanticName);
3874 }
3875
John Kessenich5d610ee2018-03-07 18:05:55 -07003876 if (builtIn == spv::BuiltInLayer) {
3877 // SPV_NV_viewport_array2 extension
3878 if (glslangMember.getQualifier().layoutViewportRelative){
3879 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3880 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3881 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003882 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003883 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3884 builder.addMemberDecoration(spvType, member,
3885 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3886 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3887 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3888 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003889 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003890 }
3891 if (glslangMember.getQualifier().layoutPassthrough) {
3892 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3893 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3894 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3895 }
chaoc771d89f2017-01-13 01:10:53 -08003896#endif
John Kessenich6090df02016-06-30 21:18:02 -06003897 }
3898
3899 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003900 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3901 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003902}
3903
John Kessenich6c292d32016-02-15 20:58:50 -07003904// Turn the expression forming the array size into an id.
3905// This is not quite trivial, because of specialization constants.
3906// Sometimes, a raw constant is turned into an Id, and sometimes
3907// a specialization constant expression is.
3908spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3909{
3910 // First, see if this is sized with a node, meaning a specialization constant:
3911 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3912 if (specNode != nullptr) {
3913 builder.clearAccessChain();
3914 specNode->traverse(this);
3915 return accessChainLoad(specNode->getAsTyped()->getType());
3916 }
qining25262b32016-05-06 17:25:16 -04003917
John Kessenich6c292d32016-02-15 20:58:50 -07003918 // Otherwise, need a compile-time (front end) size, get it:
3919 int size = arraySizes.getDimSize(dim);
3920 assert(size > 0);
3921 return builder.makeUintConstant(size);
3922}
3923
John Kessenich103bef92016-02-08 21:38:15 -07003924// Wrap the builder's accessChainLoad to:
3925// - localize handling of RelaxedPrecision
3926// - use the SPIR-V inferred type instead of another conversion of the glslang type
3927// (avoids unnecessary work and possible type punning for structures)
3928// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003929spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3930{
John Kessenich103bef92016-02-08 21:38:15 -07003931 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003932
3933 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3934 coherentFlags |= TranslateCoherent(type);
3935
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003936 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003937 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003938
John Kessenich5611c6d2018-04-05 11:25:02 -06003939 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07003940 TranslateNonUniformDecoration(type.getQualifier()),
3941 nominalTypeId,
3942 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3943 TranslateMemoryScope(coherentFlags),
3944 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003945
3946 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003947 if (type.getBasicType() == glslang::EbtBool) {
3948 if (builder.isScalarType(nominalTypeId)) {
3949 // Conversion for bool
3950 spv::Id boolType = builder.makeBoolType();
3951 if (nominalTypeId != boolType)
3952 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3953 } else if (builder.isVectorType(nominalTypeId)) {
3954 // Conversion for bvec
3955 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3956 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3957 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07003958 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
3959 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003960 }
3961 }
John Kessenich103bef92016-02-08 21:38:15 -07003962
3963 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003964}
3965
Rex Xu27253232016-02-23 17:51:09 +08003966// Wrap the builder's accessChainStore to:
3967// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003968//
3969// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003970void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3971{
3972 // Need to convert to abstract types when necessary
3973 if (type.getBasicType() == glslang::EbtBool) {
3974 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3975
3976 if (builder.isScalarType(nominalTypeId)) {
3977 // Conversion for bool
3978 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003979 if (nominalTypeId != boolType) {
3980 // keep these outside arguments, for determinant order-of-evaluation
3981 spv::Id one = builder.makeUintConstant(1);
3982 spv::Id zero = builder.makeUintConstant(0);
3983 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3984 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003985 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003986 } else if (builder.isVectorType(nominalTypeId)) {
3987 // Conversion for bvec
3988 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3989 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003990 if (nominalTypeId != bvecType) {
3991 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003992 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3993 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3994 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003995 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003996 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3997 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003998 }
3999 }
4000
Jeff Bolz36831c92018-09-05 10:11:41 -05004001 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4002 coherentFlags |= TranslateCoherent(type);
4003
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004004 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004005 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004006
Jeff Bolz36831c92018-09-05 10:11:41 -05004007 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004008 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4009 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004010 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004011}
4012
John Kessenich4bf71552016-09-02 11:20:21 -06004013// For storing when types match at the glslang level, but not might match at the
4014// SPIR-V level.
4015//
4016// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004017// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004018// as in a member-decorated way.
4019//
4020// NOTE: This function can handle any store request; if it's not special it
4021// simplifies to a simple OpStore.
4022//
4023// Implicitly uses the existing builder.accessChain as the storage target.
4024void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4025{
John Kessenichb3e24e42016-09-11 12:33:43 -06004026 // we only do the complex path here if it's an aggregate
4027 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004028 accessChainStore(type, rValue);
4029 return;
4030 }
4031
John Kessenichb3e24e42016-09-11 12:33:43 -06004032 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004033 spv::Id rType = builder.getTypeId(rValue);
4034 spv::Id lValue = builder.accessChainGetLValue();
4035 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4036 if (lType == rType) {
4037 accessChainStore(type, rValue);
4038 return;
4039 }
4040
John Kessenichb3e24e42016-09-11 12:33:43 -06004041 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004042 // where the two types were the same type in GLSL. This requires member
4043 // by member copy, recursively.
4044
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004045 // SPIR-V 1.4 added an instruction to do help do this.
4046 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4047 // However, bool in uniform space is changed to int, so
4048 // OpCopyLogical does not work for that.
4049 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4050 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4051 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4052 if (lBool == rBool) {
4053 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4054 accessChainStore(type, logicalCopy);
4055 return;
4056 }
4057 }
4058
John Kessenichb3e24e42016-09-11 12:33:43 -06004059 // If an array, copy element by element.
4060 if (type.isArray()) {
4061 glslang::TType glslangElementType(type, 0);
4062 spv::Id elementRType = builder.getContainedTypeId(rType);
4063 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4064 // get the source member
4065 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004066
John Kessenichb3e24e42016-09-11 12:33:43 -06004067 // set up the target storage
4068 builder.clearAccessChain();
4069 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004070 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4071 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004072
John Kessenichb3e24e42016-09-11 12:33:43 -06004073 // store the member
4074 multiTypeStore(glslangElementType, elementRValue);
4075 }
4076 } else {
4077 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004078
John Kessenichb3e24e42016-09-11 12:33:43 -06004079 // loop over structure members
4080 const glslang::TTypeList& members = *type.getStruct();
4081 for (int m = 0; m < (int)members.size(); ++m) {
4082 const glslang::TType& glslangMemberType = *members[m].type;
4083
4084 // get the source member
4085 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4086 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4087
4088 // set up the target storage
4089 builder.clearAccessChain();
4090 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004091 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4092 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004093
4094 // store the member
4095 multiTypeStore(glslangMemberType, memberRValue);
4096 }
John Kessenich4bf71552016-09-02 11:20:21 -06004097 }
4098}
4099
John Kessenichf85e8062015-12-19 13:57:10 -07004100// Decide whether or not this type should be
4101// decorated with offsets and strides, and if so
4102// whether std140 or std430 rules should be applied.
4103glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004104{
John Kessenichf85e8062015-12-19 13:57:10 -07004105 // has to be a block
4106 if (type.getBasicType() != glslang::EbtBlock)
4107 return glslang::ElpNone;
4108
Chao Chen3c366992018-09-19 11:41:59 -07004109 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004110 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004111 type.getQualifier().storage != glslang::EvqBuffer &&
4112 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004113 return glslang::ElpNone;
4114
4115 // return the layout to use
4116 switch (type.getQualifier().layoutPacking) {
4117 case glslang::ElpStd140:
4118 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004119 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004120 return type.getQualifier().layoutPacking;
4121 default:
4122 return glslang::ElpNone;
4123 }
John Kessenich31ed4832015-09-09 17:51:38 -06004124}
4125
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004126// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004127int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4128 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004129{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004130 int size;
John Kessenich49987892015-12-29 17:11:44 -07004131 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004132 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4133 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004134
4135 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004136}
4137
John Kessenich49987892015-12-29 17:11:44 -07004138// 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 -07004139// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004140int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4141 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004142{
John Kessenich49987892015-12-29 17:11:44 -07004143 glslang::TType elementType;
4144 elementType.shallowCopy(matrixType);
4145 elementType.clearArraySizes();
4146
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004147 int size;
John Kessenich49987892015-12-29 17:11:44 -07004148 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004149 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4150 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004151
4152 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004153}
4154
John Kessenich5e4b1242015-08-06 22:53:06 -06004155// Given a member type of a struct, realign the current offset for it, and compute
4156// the next (not yet aligned) offset for the next member, which will get aligned
4157// on the next call.
4158// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4159// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4160// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004161void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4162 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004163{
4164 // this will get a positive value when deemed necessary
4165 nextOffset = -1;
4166
John Kessenich5e4b1242015-08-06 22:53:06 -06004167 // override anything in currentOffset with user-set offset
4168 if (memberType.getQualifier().hasOffset())
4169 currentOffset = memberType.getQualifier().layoutOffset;
4170
4171 // It could be that current linker usage in glslang updated all the layoutOffset,
4172 // in which case the following code does not matter. But, that's not quite right
4173 // once cross-compilation unit GLSL validation is done, as the original user
4174 // settings are needed in layoutOffset, and then the following will come into play.
4175
John Kessenichf85e8062015-12-19 13:57:10 -07004176 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004177 if (! memberType.getQualifier().hasOffset())
4178 currentOffset = -1;
4179
4180 return;
4181 }
4182
John Kessenichf85e8062015-12-19 13:57:10 -07004183 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004184 if (currentOffset < 0)
4185 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004186
John Kessenich5e4b1242015-08-06 22:53:06 -06004187 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4188 // but possibly not yet correctly aligned.
4189
4190 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004191 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004192 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4193 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004194
4195 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004196 // TODO: make this consistent in early phases of code:
4197 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4198 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4199 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004200 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004201 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004202 int dummySize;
4203 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4204 if (componentAlignment <= 4)
4205 memberAlignment = componentAlignment;
4206 }
4207
4208 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004209 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004210
4211 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004212 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4213 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004214 glslang::RoundToPow2(currentOffset, 16);
4215
John Kessenich5e4b1242015-08-06 22:53:06 -06004216 nextOffset = currentOffset + memberSize;
4217}
4218
David Netoa901ffe2016-06-08 14:11:40 +01004219void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004220{
David Netoa901ffe2016-06-08 14:11:40 +01004221 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4222 switch (glslangBuiltIn)
4223 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004224 case glslang::EbvPointSize:
4225#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004226 case glslang::EbvClipDistance:
4227 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004228 case glslang::EbvViewportMaskNV:
4229 case glslang::EbvSecondaryPositionNV:
4230 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004231 case glslang::EbvPositionPerViewNV:
4232 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004233 case glslang::EbvTaskCountNV:
4234 case glslang::EbvPrimitiveCountNV:
4235 case glslang::EbvPrimitiveIndicesNV:
4236 case glslang::EbvClipDistancePerViewNV:
4237 case glslang::EbvCullDistancePerViewNV:
4238 case glslang::EbvLayerPerViewNV:
4239 case glslang::EbvMeshViewCountNV:
4240 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004241#endif
David Netoa901ffe2016-06-08 14:11:40 +01004242 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4243 // Alternately, we could just call this for any glslang built-in, since the
4244 // capability already guards against duplicates.
4245 TranslateBuiltInDecoration(glslangBuiltIn, false);
4246 break;
4247 default:
4248 // Capabilities were already generated when the struct was declared.
4249 break;
4250 }
John Kessenichebb50532016-05-16 19:22:05 -06004251}
4252
John Kessenich6fccb3c2016-09-19 16:01:41 -06004253bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004254{
John Kessenicheee9d532016-09-19 18:09:30 -06004255 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004256}
4257
John Kessenichd41993d2017-09-10 15:21:05 -06004258// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004259// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4260// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004261bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004262{
John Kessenich6a14f782017-12-04 02:48:10 -07004263 assert(qualifier == glslang::EvqIn ||
4264 qualifier == glslang::EvqOut ||
4265 qualifier == glslang::EvqInOut ||
4266 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004267 return qualifier != glslang::EvqConstReadOnly;
4268}
4269
4270// Is parameter pass-by-original?
4271bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4272 bool implicitThisParam)
4273{
4274 if (implicitThisParam) // implicit this
4275 return true;
4276 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004277 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004278 return paramType.containsOpaque() || // sampler, etc.
4279 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4280}
4281
John Kessenich140f3df2015-06-26 16:58:36 -06004282// Make all the functions, skeletally, without actually visiting their bodies.
4283void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4284{
John Kessenich8985fc92020-03-03 10:25:07 -07004285 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4286 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004287 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4288 if (paramPrecision != spv::NoPrecision)
4289 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004290 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004291 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004292 // Original and non-writable params pass the pointer directly and
4293 // use restrict/aliased, others are stored to a pointer in Function
4294 // memory and use RestrictPointer/AliasedPointer.
4295 if (originalParam(type.getQualifier().storage, type, false) ||
4296 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004297 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4298 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004299 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004300 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4301 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004302 }
4303 }
John Kessenichfad62972017-07-18 02:35:46 -06004304 };
4305
John Kessenich140f3df2015-06-26 16:58:36 -06004306 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4307 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004308 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004309 continue;
4310
4311 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004312 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004313 //
qining25262b32016-05-06 17:25:16 -04004314 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004315 // function. What it is an address of varies:
4316 //
John Kessenich4bf71552016-09-02 11:20:21 -06004317 // - "in" parameters not marked as "const" can be written to without modifying the calling
4318 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004319 //
4320 // - "const in" parameters can just be the r-value, as no writes need occur.
4321 //
John Kessenich4bf71552016-09-02 11:20:21 -06004322 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4323 // 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 -06004324
4325 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004326 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004327 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4328
John Kessenich155d3512019-08-08 23:29:20 -06004329#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004330 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4331 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004332#else
4333 bool implicitThis = false;
4334#endif
John Kessenich37789792017-03-21 23:56:40 -06004335
John Kessenichfad62972017-07-18 02:35:46 -06004336 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004337 for (int p = 0; p < (int)parameters.size(); ++p) {
4338 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4339 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004340 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004341 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004342 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004343 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4344 else
John Kessenich4bf71552016-09-02 11:20:21 -06004345 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004346 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004347 paramTypes.push_back(typeId);
4348 }
4349
4350 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004351 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4352 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004353 glslFunction->getName().c_str(), paramTypes,
4354 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004355 if (implicitThis)
4356 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004357
4358 // Track function to emit/call later
4359 functionMap[glslFunction->getName().c_str()] = function;
4360
4361 // Set the parameter id's
4362 for (int p = 0; p < (int)parameters.size(); ++p) {
4363 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4364 // give a name too
4365 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004366
4367 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004368 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004369 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004370 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004371 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004372 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004373 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004374 }
4375 }
4376}
4377
4378// Process all the initializers, while skipping the functions and link objects
4379void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4380{
4381 builder.setBuildPoint(shaderEntry->getLastBlock());
4382 for (int i = 0; i < (int)initializers.size(); ++i) {
4383 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004384 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4385 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004386
4387 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004388 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004389 initializer->traverse(this);
4390 }
4391 }
4392}
4393
4394// Process all the functions, while skipping initializers.
4395void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4396{
4397 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4398 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004399 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004400 node->traverse(this);
4401 }
4402}
4403
4404void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4405{
qining25262b32016-05-06 17:25:16 -04004406 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004407 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004408 currentFunction = functionMap[node->getName().c_str()];
4409 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004410 builder.setBuildPoint(functionBlock);
4411}
4412
John Kessenich8985fc92020-03-03 10:25:07 -07004413void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4414 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004415{
Rex Xufc618912015-09-09 16:42:49 +08004416 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004417
4418 glslang::TSampler sampler = {};
4419 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004420#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004421 bool f16ShadowCompare = false;
4422#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004423 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004424 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4425 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004426#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004427 f16ShadowCompare = sampler.shadow &&
4428 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004429#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004430 }
4431
John Kessenich140f3df2015-06-26 16:58:36 -06004432 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4433 builder.clearAccessChain();
4434 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004435
John Kessenicha28f7a72019-08-06 07:00:58 -06004436#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004437 // Special case l-value operands
4438 bool lvalue = false;
4439 switch (node.getOp()) {
4440 case glslang::EOpImageAtomicAdd:
4441 case glslang::EOpImageAtomicMin:
4442 case glslang::EOpImageAtomicMax:
4443 case glslang::EOpImageAtomicAnd:
4444 case glslang::EOpImageAtomicOr:
4445 case glslang::EOpImageAtomicXor:
4446 case glslang::EOpImageAtomicExchange:
4447 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004448 case glslang::EOpImageAtomicLoad:
4449 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004450 if (i == 0)
4451 lvalue = true;
4452 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004453 case glslang::EOpSparseImageLoad:
4454 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4455 lvalue = true;
4456 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004457 case glslang::EOpSparseTexture:
4458 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4459 lvalue = true;
4460 break;
4461 case glslang::EOpSparseTextureClamp:
4462 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4463 lvalue = true;
4464 break;
4465 case glslang::EOpSparseTextureLod:
4466 case glslang::EOpSparseTextureOffset:
4467 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4468 lvalue = true;
4469 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004470 case glslang::EOpSparseTextureFetch:
4471 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4472 lvalue = true;
4473 break;
4474 case glslang::EOpSparseTextureFetchOffset:
4475 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4476 lvalue = true;
4477 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004478 case glslang::EOpSparseTextureLodOffset:
4479 case glslang::EOpSparseTextureGrad:
4480 case glslang::EOpSparseTextureOffsetClamp:
4481 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4482 lvalue = true;
4483 break;
4484 case glslang::EOpSparseTextureGradOffset:
4485 case glslang::EOpSparseTextureGradClamp:
4486 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4487 lvalue = true;
4488 break;
4489 case glslang::EOpSparseTextureGradOffsetClamp:
4490 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4491 lvalue = true;
4492 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004493 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004494 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4495 lvalue = true;
4496 break;
4497 case glslang::EOpSparseTextureGatherOffset:
4498 case glslang::EOpSparseTextureGatherOffsets:
4499 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4500 lvalue = true;
4501 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004502 case glslang::EOpSparseTextureGatherLod:
4503 if (i == 3)
4504 lvalue = true;
4505 break;
4506 case glslang::EOpSparseTextureGatherLodOffset:
4507 case glslang::EOpSparseTextureGatherLodOffsets:
4508 if (i == 4)
4509 lvalue = true;
4510 break;
Rex Xu129799a2017-07-05 17:23:28 +08004511 case glslang::EOpSparseImageLoadLod:
4512 if (i == 3)
4513 lvalue = true;
4514 break;
Chao Chen3a137962018-09-19 11:41:27 -07004515 case glslang::EOpImageSampleFootprintNV:
4516 if (i == 4)
4517 lvalue = true;
4518 break;
4519 case glslang::EOpImageSampleFootprintClampNV:
4520 case glslang::EOpImageSampleFootprintLodNV:
4521 if (i == 5)
4522 lvalue = true;
4523 break;
4524 case glslang::EOpImageSampleFootprintGradNV:
4525 if (i == 6)
4526 lvalue = true;
4527 break;
4528 case glslang::EOpImageSampleFootprintGradClampNV:
4529 if (i == 7)
4530 lvalue = true;
4531 break;
Rex Xufc618912015-09-09 16:42:49 +08004532 default:
4533 break;
4534 }
4535
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004536 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004537 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004538 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4539 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4540 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004541#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004542 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004543 }
4544}
4545
John Kessenichfc51d282015-08-19 13:34:18 -06004546void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004547{
John Kessenichfc51d282015-08-19 13:34:18 -06004548 builder.clearAccessChain();
4549 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004550 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004551}
John Kessenich140f3df2015-06-26 16:58:36 -06004552
John Kessenichfc51d282015-08-19 13:34:18 -06004553spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4554{
John Kesseniche485c7a2017-05-31 18:50:53 -06004555 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004556 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004557
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004558 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004559
John Kessenichfc51d282015-08-19 13:34:18 -06004560 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004561
John Kessenichf43c7392019-03-31 10:51:57 -06004562 const glslang::TType &imageType = node->getAsAggregate()
4563 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4564 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004565 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004566#ifdef GLSLANG_WEB
4567 const bool f16ShadowCompare = false;
4568#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004569 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004570 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4571 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004572#endif
4573
John Kessenichf43c7392019-03-31 10:51:57 -06004574 const auto signExtensionMask = [&]() {
4575 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4576 if (sampler.type == glslang::EbtUint)
4577 return spv::ImageOperandsZeroExtendMask;
4578 else if (sampler.type == glslang::EbtInt)
4579 return spv::ImageOperandsSignExtendMask;
4580 }
4581 return spv::ImageOperandsMaskNone;
4582 };
4583
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004584 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4585
John Kessenichfc51d282015-08-19 13:34:18 -06004586 std::vector<spv::Id> arguments;
4587 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004588 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004589 else
4590 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004591 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004592
4593 spv::Builder::TextureParameters params = { };
4594 params.sampler = arguments[0];
4595
Rex Xu04db3f52015-09-16 11:44:02 +08004596 glslang::TCrackedTextureOp cracked;
4597 node->crackTexture(sampler, cracked);
4598
amhagan05506bb2017-06-13 16:53:02 -04004599 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004600
John Kessenichfc51d282015-08-19 13:34:18 -06004601 // Check for queries
4602 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004603 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4604 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004605 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004606
John Kessenichfc51d282015-08-19 13:34:18 -06004607 switch (node->getOp()) {
4608 case glslang::EOpImageQuerySize:
4609 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004610 if (arguments.size() > 1) {
4611 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004612 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004613 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004614 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004615#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004616 case glslang::EOpImageQuerySamples:
4617 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004618 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004619 case glslang::EOpTextureQueryLod:
4620 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004621 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004622 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004623 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004624 case glslang::EOpSparseTexelsResident:
4625 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004626#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004627 default:
4628 assert(0);
4629 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004630 }
John Kessenich140f3df2015-06-26 16:58:36 -06004631 }
4632
LoopDawg4425f242018-02-18 11:40:01 -07004633 int components = node->getType().getVectorSize();
4634
4635 if (node->getOp() == glslang::EOpTextureFetch) {
4636 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4637 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4638 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4639 // here around e.g. which ones return scalars or other types.
4640 components = 4;
4641 }
4642
4643 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4644
4645 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4646
Rex Xufc618912015-09-09 16:42:49 +08004647 // Check for image functions other than queries
4648 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004649 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004650 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004651 spv::IdImmediate image = { true, *(opIt++) };
4652 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004653
4654 // Handle subpass operations
4655 // TODO: GLSL should change to have the "MS" only on the type rather than the
4656 // built-in function.
4657 if (cracked.subpass) {
4658 // add on the (0,0) coordinate
4659 spv::Id zero = builder.makeIntConstant(0);
4660 std::vector<spv::Id> comps;
4661 comps.push_back(zero);
4662 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004663 spv::IdImmediate coord = { true,
4664 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4665 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004666 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4667 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004668 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004669 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4670 }
4671 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004672 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004673 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004674 spv::IdImmediate imageOperand = { true, *(opIt++) };
4675 operands.push_back(imageOperand);
4676 }
John Kessenich6c292d32016-02-15 20:58:50 -07004677 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004678 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4679 builder.setPrecision(result, precision);
4680 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004681 }
4682
John Kessenich149afc32018-08-14 13:31:43 -06004683 spv::IdImmediate coord = { true, *(opIt++) };
4684 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004685 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004686 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004687 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004688 mask = mask | spv::ImageOperandsSampleMask;
4689 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004690 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004691 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4692 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004693 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004694 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004695 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4696 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004697 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004698 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004699 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4700 operands.push_back(imageOperands);
4701 }
4702 if (mask & spv::ImageOperandsSampleMask) {
4703 spv::IdImmediate imageOperand = { true, *opIt++ };
4704 operands.push_back(imageOperand);
4705 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004706 if (mask & spv::ImageOperandsLodMask) {
4707 spv::IdImmediate imageOperand = { true, *opIt++ };
4708 operands.push_back(imageOperand);
4709 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004710 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004711 spv::IdImmediate imageOperand = { true,
4712 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004713 operands.push_back(imageOperand);
4714 }
4715
John Kessenich149afc32018-08-14 13:31:43 -06004716 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004717 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004718
John Kessenich149afc32018-08-14 13:31:43 -06004719 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004720 builder.setPrecision(result[0], precision);
4721
4722 // If needed, add a conversion constructor to the proper size.
4723 if (components != node->getType().getVectorSize())
4724 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4725
4726 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004727 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004728
Jeff Bolz36831c92018-09-05 10:11:41 -05004729 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004730 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004731 spv::IdImmediate texel = { true, *(opIt + 1) };
4732 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004733 } else {
4734 spv::IdImmediate texel = { true, *opIt };
4735 operands.push_back(texel);
4736 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004737
4738 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004739 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004740 mask = mask | spv::ImageOperandsSampleMask;
4741 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004742 if (cracked.lod) {
4743 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4744 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4745 mask = mask | spv::ImageOperandsLodMask;
4746 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004747 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4748 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004749 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004750 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004751 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4752 operands.push_back(imageOperands);
4753 }
4754 if (mask & spv::ImageOperandsSampleMask) {
4755 spv::IdImmediate imageOperand = { true, *opIt++ };
4756 operands.push_back(imageOperand);
4757 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004758 if (mask & spv::ImageOperandsLodMask) {
4759 spv::IdImmediate imageOperand = { true, *opIt++ };
4760 operands.push_back(imageOperand);
4761 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004762 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004763 spv::IdImmediate imageOperand = { true,
4764 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004765 operands.push_back(imageOperand);
4766 }
4767
John Kessenich56bab042015-09-16 10:54:31 -06004768 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004769 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004770 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004771 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004772 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4773 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004774 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004775 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004776 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4777
Jeff Bolz36831c92018-09-05 10:11:41 -05004778 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004779 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004780 mask = mask | spv::ImageOperandsSampleMask;
4781 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004782 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004783 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4784 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4785
Jeff Bolz36831c92018-09-05 10:11:41 -05004786 mask = mask | spv::ImageOperandsLodMask;
4787 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004788 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4789 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004790 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004791 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004792 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004793 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004794 }
4795 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004796 spv::IdImmediate imageOperand = { true, *opIt++ };
4797 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004798 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004799 if (mask & spv::ImageOperandsLodMask) {
4800 spv::IdImmediate imageOperand = { true, *opIt++ };
4801 operands.push_back(imageOperand);
4802 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004803 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004804 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4805 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004806 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004807 }
4808
4809 // Create the return type that was a special structure
4810 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004811 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004812 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4813 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4814
4815 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4816
4817 // Decode the return type
4818 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4819 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004820 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004821 // Process image atomic operations
4822
4823 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4824 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004825 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004826 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004827 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004828
Jeff Bolz36831c92018-09-05 10:11:41 -05004829 spv::Id resultTypeId;
4830 // imageAtomicStore has a void return type so base the pointer type on
4831 // the type of the value operand.
4832 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004833 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004834 } else {
4835 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4836 }
John Kessenich56bab042015-09-16 10:54:31 -06004837 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004838
4839 std::vector<spv::Id> operands;
4840 operands.push_back(pointer);
4841 for (; opIt != arguments.end(); ++opIt)
4842 operands.push_back(*opIt);
4843
John Kessenich8985fc92020-03-03 10:25:07 -07004844 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4845 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004846 }
4847 }
4848
John Kessenicha28f7a72019-08-06 07:00:58 -06004849#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004850 // Check for fragment mask functions other than queries
4851 if (cracked.fragMask) {
4852 assert(sampler.ms);
4853
4854 auto opIt = arguments.begin();
4855 std::vector<spv::Id> operands;
4856
4857 // Extract the image if necessary
4858 if (builder.isSampledImage(params.sampler))
4859 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4860
4861 operands.push_back(params.sampler);
4862 ++opIt;
4863
4864 if (sampler.isSubpass()) {
4865 // add on the (0,0) coordinate
4866 spv::Id zero = builder.makeIntConstant(0);
4867 std::vector<spv::Id> comps;
4868 comps.push_back(zero);
4869 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004870 operands.push_back(builder.makeCompositeConstant(
4871 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04004872 }
4873
4874 for (; opIt != arguments.end(); ++opIt)
4875 operands.push_back(*opIt);
4876
4877 spv::Op fragMaskOp = spv::OpNop;
4878 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4879 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4880 else if (node->getOp() == glslang::EOpFragmentFetch)
4881 fragMaskOp = spv::OpFragmentFetchAMD;
4882
4883 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4884 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4885 return builder.createOp(fragMaskOp, resultType(), operands);
4886 }
4887#endif
4888
Rex Xufc618912015-09-09 16:42:49 +08004889 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004890 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004891 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004892 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004893
John Kessenichfc51d282015-08-19 13:34:18 -06004894 // check for bias argument
4895 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004896 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004897 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004898 if (cracked.gather)
4899 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004900
4901 if (f16ShadowCompare)
4902 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004903 if (cracked.offset)
4904 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004905 else if (cracked.offsets)
4906 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004907 if (cracked.grad)
4908 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004909 if (cracked.lodClamp)
4910 ++nonBiasArgCount;
4911 if (sparse)
4912 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004913 if (imageFootprint)
4914 //Following three extra arguments
4915 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4916 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004917 if ((int)arguments.size() > nonBiasArgCount)
4918 bias = true;
4919 }
4920
John Kessenicha5c33d62016-06-02 23:45:21 -06004921 // See if the sampler param should really be just the SPV image part
4922 if (cracked.fetch) {
4923 // a fetch needs to have the image extracted first
4924 if (builder.isSampledImage(params.sampler))
4925 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4926 }
4927
John Kessenicha28f7a72019-08-06 07:00:58 -06004928#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004929 if (cracked.gather) {
4930 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4931 if (bias || cracked.lod ||
4932 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4933 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004934 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004935 }
4936 }
4937#endif
4938
John Kessenichfc51d282015-08-19 13:34:18 -06004939 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004940
John Kessenichfc51d282015-08-19 13:34:18 -06004941 params.coords = arguments[1];
4942 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004943 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004944
4945 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004946 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004947 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004948 ++extraArgs;
4949 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004950 params.Dref = arguments[2];
4951 ++extraArgs;
4952 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004953 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004954 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004955 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004956 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004957 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004958 dRefComp = builder.getNumComponents(params.coords) - 1;
4959 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07004960 params.Dref = builder.createCompositeExtract(params.coords,
4961 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06004962 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004963
4964 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004965 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004966 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004967 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004968 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4969 !(glslangIntermediate->getStage() == EShLangCompute &&
4970 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004971 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4972 noImplicitLod = true;
4973 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004974
4975 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004976 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004977 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004978 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004979 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004980
4981 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004982 if (cracked.grad) {
4983 params.gradX = arguments[2 + extraArgs];
4984 params.gradY = arguments[3 + extraArgs];
4985 extraArgs += 2;
4986 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004987
4988 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004989 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004990 params.offset = arguments[2 + extraArgs];
4991 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004992 } else if (cracked.offsets) {
4993 params.offsets = arguments[2 + extraArgs];
4994 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004995 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004996
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004997#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004998 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004999 if (cracked.lodClamp) {
5000 params.lodClamp = arguments[2 + extraArgs];
5001 ++extraArgs;
5002 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005003 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005004 if (sparse) {
5005 params.texelOut = arguments[2 + extraArgs];
5006 ++extraArgs;
5007 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005008 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005009 if (cracked.gather && ! sampler.shadow) {
5010 // default component is 0, if missing, otherwise an argument
5011 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005012 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005013 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005014 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005015 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005016 }
Chao Chen3a137962018-09-19 11:41:27 -07005017 spv::Id resultStruct = spv::NoResult;
5018 if (imageFootprint) {
5019 //Following three extra arguments
5020 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5021 params.granularity = arguments[2 + extraArgs];
5022 params.coarse = arguments[3 + extraArgs];
5023 resultStruct = arguments[4 + extraArgs];
5024 extraArgs += 3;
5025 }
5026#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005027 // bias
5028 if (bias) {
5029 params.bias = arguments[2 + extraArgs];
5030 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005031 }
John Kessenichfc51d282015-08-19 13:34:18 -06005032
John Kessenicha28f7a72019-08-06 07:00:58 -06005033#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005034 if (imageFootprint) {
5035 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5036 builder.addCapability(spv::CapabilityImageFootprintNV);
5037
5038
5039 //resultStructType(OpenGL type) contains 5 elements:
5040 //struct gl_TextureFootprint2DNV {
5041 // uvec2 anchor;
5042 // uvec2 offset;
5043 // uvec2 mask;
5044 // uint lod;
5045 // uint granularity;
5046 //};
5047 //or
5048 //struct gl_TextureFootprint3DNV {
5049 // uvec3 anchor;
5050 // uvec3 offset;
5051 // uvec2 mask;
5052 // uint lod;
5053 // uint granularity;
5054 //};
5055 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5056 assert(builder.isStructType(resultStructType));
5057
5058 //resType (SPIR-V type) contains 6 elements:
5059 //Member 0 must be a Boolean type scalar(LOD),
5060 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5061 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5062 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5063 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5064 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5065 std::vector<spv::Id> members;
5066 members.push_back(resultType());
5067 for (int i = 0; i < 5; i++) {
5068 members.push_back(builder.getContainedTypeId(resultStructType, i));
5069 }
5070 spv::Id resType = builder.makeStructType(members, "ResType");
5071
5072 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005073 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5074 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005075
5076 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5077 for (int i = 0; i < 5; i++) {
5078 builder.clearAccessChain();
5079 builder.setAccessChainLValue(resultStruct);
5080
5081 //Accessing to a struct we created, no coherent flag is set
5082 spv::Builder::AccessChain::CoherentFlags flags;
5083 flags.clear();
5084
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005085 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005086 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5087 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005088 }
5089 return builder.createCompositeExtract(res, resultType(), 0);
5090 }
5091#endif
5092
John Kessenich65336482016-06-16 14:06:26 -06005093 // projective component (might not to move)
5094 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5095 // are divided by the last component of P."
5096 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5097 // unused components will appear after all used components."
5098 if (cracked.proj) {
5099 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5100 int projTargetComp;
5101 switch (sampler.dim) {
5102 case glslang::Esd1D: projTargetComp = 1; break;
5103 case glslang::Esd2D: projTargetComp = 2; break;
5104 case glslang::EsdRect: projTargetComp = 2; break;
5105 default: projTargetComp = projSourceComp; break;
5106 }
5107 // copy the projective coordinate if we have to
5108 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005109 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005110 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005111 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005112 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005113 }
5114 }
5115
John Kessenichf8d1d742019-10-21 06:55:11 -06005116#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005117 // nonprivate
5118 if (imageType.getQualifier().nonprivate) {
5119 params.nonprivate = true;
5120 }
5121
5122 // volatile
5123 if (imageType.getQualifier().volatil) {
5124 params.volatil = true;
5125 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005126#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005127
St0fFa1184dd2018-04-09 21:08:14 +02005128 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005129 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5130 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005131 );
LoopDawg4425f242018-02-18 11:40:01 -07005132
5133 if (components != node->getType().getVectorSize())
5134 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5135
5136 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005137}
5138
5139spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5140{
5141 // Grab the function's pointer from the previously created function
5142 spv::Function* function = functionMap[node->getName().c_str()];
5143 if (! function)
5144 return 0;
5145
5146 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5147 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5148
5149 // See comments in makeFunctions() for details about the semantics for parameter passing.
5150 //
5151 // These imply we need a four step process:
5152 // 1. Evaluate the arguments
5153 // 2. Allocate and make copies of in, out, and inout arguments
5154 // 3. Make the call
5155 // 4. Copy back the results
5156
John Kessenichd3ed90b2018-05-04 11:43:03 -06005157 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005158 std::vector<spv::Builder::AccessChain> lValues;
5159 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005160 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005161 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005162 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005163 // build l-value
5164 builder.clearAccessChain();
5165 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005166 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005167 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005168 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005169 // save l-value
5170 lValues.push_back(builder.getAccessChain());
5171 } else {
5172 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005173 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005174 }
5175 }
5176
5177 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5178 // copy the original into that space.
5179 //
5180 // Also, build up the list of actual arguments to pass in for the call
5181 int lValueCount = 0;
5182 int rValueCount = 0;
5183 std::vector<spv::Id> spvArgs;
5184 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5185 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005186 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005187 builder.setAccessChain(lValues[lValueCount]);
5188 arg = builder.accessChainGetLValue();
5189 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005190 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005191 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005192 arg = builder.createVariable(spv::StorageClassFunction,
5193 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005194 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5195 // need to copy the input into output space
5196 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005197 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005198 builder.clearAccessChain();
5199 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005200 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005201 }
5202 ++lValueCount;
5203 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005204 // process r-value, which involves a copy for a type mismatch
5205 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5206 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5207 builder.clearAccessChain();
5208 builder.setAccessChainLValue(argCopy);
5209 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5210 arg = builder.createLoad(argCopy);
5211 } else
5212 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005213 ++rValueCount;
5214 }
5215 spvArgs.push_back(arg);
5216 }
5217
5218 // 3. Make the call.
5219 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005220 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005221
5222 // 4. Copy back out an "out" arguments.
5223 lValueCount = 0;
5224 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005225 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005226 ++lValueCount;
5227 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005228 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5229 spv::Id copy = builder.createLoad(spvArgs[a]);
5230 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005231 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005232 }
5233 ++lValueCount;
5234 }
5235 }
5236
5237 return result;
5238}
5239
5240// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005241spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005242 spv::Id typeId, spv::Id left, spv::Id right,
5243 glslang::TBasicType typeProxy, bool reduceComparison)
5244{
John Kessenich66011cb2018-03-06 16:12:04 -07005245 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5246 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005247 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005248
5249 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005250 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005251 bool comparison = false;
5252
5253 switch (op) {
5254 case glslang::EOpAdd:
5255 case glslang::EOpAddAssign:
5256 if (isFloat)
5257 binOp = spv::OpFAdd;
5258 else
5259 binOp = spv::OpIAdd;
5260 break;
5261 case glslang::EOpSub:
5262 case glslang::EOpSubAssign:
5263 if (isFloat)
5264 binOp = spv::OpFSub;
5265 else
5266 binOp = spv::OpISub;
5267 break;
5268 case glslang::EOpMul:
5269 case glslang::EOpMulAssign:
5270 if (isFloat)
5271 binOp = spv::OpFMul;
5272 else
5273 binOp = spv::OpIMul;
5274 break;
5275 case glslang::EOpVectorTimesScalar:
5276 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005277 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005278 if (builder.isVector(right))
5279 std::swap(left, right);
5280 assert(builder.isScalar(right));
5281 needMatchingVectors = false;
5282 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005283 } else if (isFloat)
5284 binOp = spv::OpFMul;
5285 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005286 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005287 break;
5288 case glslang::EOpVectorTimesMatrix:
5289 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005290 binOp = spv::OpVectorTimesMatrix;
5291 break;
5292 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005293 binOp = spv::OpMatrixTimesVector;
5294 break;
5295 case glslang::EOpMatrixTimesScalar:
5296 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005297 binOp = spv::OpMatrixTimesScalar;
5298 break;
5299 case glslang::EOpMatrixTimesMatrix:
5300 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005301 binOp = spv::OpMatrixTimesMatrix;
5302 break;
5303 case glslang::EOpOuterProduct:
5304 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005305 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005306 break;
5307
5308 case glslang::EOpDiv:
5309 case glslang::EOpDivAssign:
5310 if (isFloat)
5311 binOp = spv::OpFDiv;
5312 else if (isUnsigned)
5313 binOp = spv::OpUDiv;
5314 else
5315 binOp = spv::OpSDiv;
5316 break;
5317 case glslang::EOpMod:
5318 case glslang::EOpModAssign:
5319 if (isFloat)
5320 binOp = spv::OpFMod;
5321 else if (isUnsigned)
5322 binOp = spv::OpUMod;
5323 else
5324 binOp = spv::OpSMod;
5325 break;
5326 case glslang::EOpRightShift:
5327 case glslang::EOpRightShiftAssign:
5328 if (isUnsigned)
5329 binOp = spv::OpShiftRightLogical;
5330 else
5331 binOp = spv::OpShiftRightArithmetic;
5332 break;
5333 case glslang::EOpLeftShift:
5334 case glslang::EOpLeftShiftAssign:
5335 binOp = spv::OpShiftLeftLogical;
5336 break;
5337 case glslang::EOpAnd:
5338 case glslang::EOpAndAssign:
5339 binOp = spv::OpBitwiseAnd;
5340 break;
5341 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005342 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005343 binOp = spv::OpLogicalAnd;
5344 break;
5345 case glslang::EOpInclusiveOr:
5346 case glslang::EOpInclusiveOrAssign:
5347 binOp = spv::OpBitwiseOr;
5348 break;
5349 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005350 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005351 binOp = spv::OpLogicalOr;
5352 break;
5353 case glslang::EOpExclusiveOr:
5354 case glslang::EOpExclusiveOrAssign:
5355 binOp = spv::OpBitwiseXor;
5356 break;
5357 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005358 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005359 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005360 break;
5361
Ian Romanickb3bd4022019-01-21 08:57:25 -08005362 case glslang::EOpAbsDifference:
5363 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5364 break;
5365
5366 case glslang::EOpAddSaturate:
5367 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5368 break;
5369
5370 case glslang::EOpSubSaturate:
5371 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5372 break;
5373
5374 case glslang::EOpAverage:
5375 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5376 break;
5377
5378 case glslang::EOpAverageRounded:
5379 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5380 break;
5381
5382 case glslang::EOpMul32x16:
5383 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5384 break;
5385
John Kessenich140f3df2015-06-26 16:58:36 -06005386 case glslang::EOpLessThan:
5387 case glslang::EOpGreaterThan:
5388 case glslang::EOpLessThanEqual:
5389 case glslang::EOpGreaterThanEqual:
5390 case glslang::EOpEqual:
5391 case glslang::EOpNotEqual:
5392 case glslang::EOpVectorEqual:
5393 case glslang::EOpVectorNotEqual:
5394 comparison = true;
5395 break;
5396 default:
5397 break;
5398 }
5399
John Kessenich7c1aa102015-10-15 13:29:11 -06005400 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005401 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005402 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005403 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5404 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005405 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005406
5407 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005408 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005409 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005410
qining25262b32016-05-06 17:25:16 -04005411 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005412 decorations.addNoContraction(builder, result);
5413 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005414 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005415 }
5416
5417 if (! comparison)
5418 return 0;
5419
John Kessenich7c1aa102015-10-15 13:29:11 -06005420 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005421
John Kessenich4583b612016-08-07 19:14:22 -06005422 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005423 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5424 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005425 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005426 return result;
5427 }
John Kessenich140f3df2015-06-26 16:58:36 -06005428
5429 switch (op) {
5430 case glslang::EOpLessThan:
5431 if (isFloat)
5432 binOp = spv::OpFOrdLessThan;
5433 else if (isUnsigned)
5434 binOp = spv::OpULessThan;
5435 else
5436 binOp = spv::OpSLessThan;
5437 break;
5438 case glslang::EOpGreaterThan:
5439 if (isFloat)
5440 binOp = spv::OpFOrdGreaterThan;
5441 else if (isUnsigned)
5442 binOp = spv::OpUGreaterThan;
5443 else
5444 binOp = spv::OpSGreaterThan;
5445 break;
5446 case glslang::EOpLessThanEqual:
5447 if (isFloat)
5448 binOp = spv::OpFOrdLessThanEqual;
5449 else if (isUnsigned)
5450 binOp = spv::OpULessThanEqual;
5451 else
5452 binOp = spv::OpSLessThanEqual;
5453 break;
5454 case glslang::EOpGreaterThanEqual:
5455 if (isFloat)
5456 binOp = spv::OpFOrdGreaterThanEqual;
5457 else if (isUnsigned)
5458 binOp = spv::OpUGreaterThanEqual;
5459 else
5460 binOp = spv::OpSGreaterThanEqual;
5461 break;
5462 case glslang::EOpEqual:
5463 case glslang::EOpVectorEqual:
5464 if (isFloat)
5465 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005466 else if (isBool)
5467 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005468 else
5469 binOp = spv::OpIEqual;
5470 break;
5471 case glslang::EOpNotEqual:
5472 case glslang::EOpVectorNotEqual:
5473 if (isFloat)
5474 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005475 else if (isBool)
5476 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005477 else
5478 binOp = spv::OpINotEqual;
5479 break;
5480 default:
5481 break;
5482 }
5483
qining25262b32016-05-06 17:25:16 -04005484 if (binOp != spv::OpNop) {
5485 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005486 decorations.addNoContraction(builder, result);
5487 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005488 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005489 }
John Kessenich140f3df2015-06-26 16:58:36 -06005490
5491 return 0;
5492}
5493
John Kessenich04bb8a02015-12-12 12:28:14 -07005494//
5495// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5496// These can be any of:
5497//
5498// matrix * scalar
5499// scalar * matrix
5500// matrix * matrix linear algebraic
5501// matrix * vector
5502// vector * matrix
5503// matrix * matrix componentwise
5504// matrix op matrix op in {+, -, /}
5505// matrix op scalar op in {+, -, /}
5506// scalar op matrix op in {+, -, /}
5507//
John Kessenichead86222018-03-28 18:01:20 -06005508spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5509 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005510{
5511 bool firstClass = true;
5512
5513 // First, handle first-class matrix operations (* and matrix/scalar)
5514 switch (op) {
5515 case spv::OpFDiv:
5516 if (builder.isMatrix(left) && builder.isScalar(right)) {
5517 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005518 spv::Id resultType = builder.getTypeId(right);
5519 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005520 op = spv::OpMatrixTimesScalar;
5521 } else
5522 firstClass = false;
5523 break;
5524 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005525 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005526 std::swap(left, right);
5527 assert(builder.isScalar(right));
5528 break;
5529 case spv::OpVectorTimesMatrix:
5530 assert(builder.isVector(left));
5531 assert(builder.isMatrix(right));
5532 break;
5533 case spv::OpMatrixTimesVector:
5534 assert(builder.isMatrix(left));
5535 assert(builder.isVector(right));
5536 break;
5537 case spv::OpMatrixTimesMatrix:
5538 assert(builder.isMatrix(left));
5539 assert(builder.isMatrix(right));
5540 break;
5541 default:
5542 firstClass = false;
5543 break;
5544 }
5545
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005546 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5547 firstClass = true;
5548
qining25262b32016-05-06 17:25:16 -04005549 if (firstClass) {
5550 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005551 decorations.addNoContraction(builder, result);
5552 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005553 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005554 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005555
LoopDawg592860c2016-06-09 08:57:35 -06005556 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005557 // The result type of all of them is the same type as the (a) matrix operand.
5558 // The algorithm is to:
5559 // - break the matrix(es) into vectors
5560 // - smear any scalar to a vector
5561 // - do vector operations
5562 // - make a matrix out the vector results
5563 switch (op) {
5564 case spv::OpFAdd:
5565 case spv::OpFSub:
5566 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005567 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005568 case spv::OpFMul:
5569 {
5570 // one time set up...
5571 bool leftMat = builder.isMatrix(left);
5572 bool rightMat = builder.isMatrix(right);
5573 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5574 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5575 spv::Id scalarType = builder.getScalarTypeId(typeId);
5576 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5577 std::vector<spv::Id> results;
5578 spv::Id smearVec = spv::NoResult;
5579 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005580 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005581 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005582 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005583
5584 // do each vector op
5585 for (unsigned int c = 0; c < numCols; ++c) {
5586 std::vector<unsigned int> indexes;
5587 indexes.push_back(c);
5588 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5589 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005590 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005591 decorations.addNoContraction(builder, result);
5592 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005593 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005594 }
5595
5596 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005597 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005598 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005599 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005600 }
5601 default:
5602 assert(0);
5603 return spv::NoResult;
5604 }
5605}
5606
John Kessenichead86222018-03-28 18:01:20 -06005607spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005608 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005609{
5610 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005611 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005612 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005613 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5614 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005615
5616 switch (op) {
5617 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005618 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005619 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005620 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005621 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005622 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005623 unaryOp = spv::OpSNegate;
5624 break;
5625
5626 case glslang::EOpLogicalNot:
5627 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005628 unaryOp = spv::OpLogicalNot;
5629 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005630 case glslang::EOpBitwiseNot:
5631 unaryOp = spv::OpNot;
5632 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005633
John Kessenich140f3df2015-06-26 16:58:36 -06005634 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005635 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005636 break;
5637 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005638 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005639 break;
5640 case glslang::EOpTranspose:
5641 unaryOp = spv::OpTranspose;
5642 break;
5643
5644 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005645 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005646 break;
5647 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005648 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005649 break;
5650 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005651 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005652 break;
5653 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005654 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005655 break;
5656 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005657 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005658 break;
5659 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005660 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005661 break;
5662 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005663 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005664 break;
5665 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005666 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005667 break;
5668
5669 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005670 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005671 break;
5672 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005673 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005674 break;
5675 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005676 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005677 break;
5678 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005679 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005680 break;
5681 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005682 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005683 break;
5684 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005685 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005686 break;
5687
5688 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005689 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005690 break;
5691 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005692 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005693 break;
5694
5695 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005696 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005697 break;
5698 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005699 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005700 break;
5701 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005702 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005703 break;
5704 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005705 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005706 break;
5707 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005708 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005709 break;
5710 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005711 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005712 break;
5713
5714 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005715 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005716 break;
5717 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005718 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005719 break;
5720 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005721 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005722 break;
5723 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005724 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005725 break;
5726 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005727 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005728 break;
5729 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005730 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005731 break;
5732
5733 case glslang::EOpIsNan:
5734 unaryOp = spv::OpIsNan;
5735 break;
5736 case glslang::EOpIsInf:
5737 unaryOp = spv::OpIsInf;
5738 break;
LoopDawg592860c2016-06-09 08:57:35 -06005739 case glslang::EOpIsFinite:
5740 unaryOp = spv::OpIsFinite;
5741 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005742
Rex Xucbc426e2015-12-15 16:03:10 +08005743 case glslang::EOpFloatBitsToInt:
5744 case glslang::EOpFloatBitsToUint:
5745 case glslang::EOpIntBitsToFloat:
5746 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005747 case glslang::EOpDoubleBitsToInt64:
5748 case glslang::EOpDoubleBitsToUint64:
5749 case glslang::EOpInt64BitsToDouble:
5750 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005751 case glslang::EOpFloat16BitsToInt16:
5752 case glslang::EOpFloat16BitsToUint16:
5753 case glslang::EOpInt16BitsToFloat16:
5754 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005755 unaryOp = spv::OpBitcast;
5756 break;
5757
John Kessenich140f3df2015-06-26 16:58:36 -06005758 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005759 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005760 break;
5761 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005762 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005763 break;
5764 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005765 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005766 break;
5767 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005768 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005769 break;
5770 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005771 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005772 break;
5773 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005774 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005775 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005776#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005777 case glslang::EOpPackSnorm4x8:
5778 libCall = spv::GLSLstd450PackSnorm4x8;
5779 break;
5780 case glslang::EOpUnpackSnorm4x8:
5781 libCall = spv::GLSLstd450UnpackSnorm4x8;
5782 break;
5783 case glslang::EOpPackUnorm4x8:
5784 libCall = spv::GLSLstd450PackUnorm4x8;
5785 break;
5786 case glslang::EOpUnpackUnorm4x8:
5787 libCall = spv::GLSLstd450UnpackUnorm4x8;
5788 break;
5789 case glslang::EOpPackDouble2x32:
5790 libCall = spv::GLSLstd450PackDouble2x32;
5791 break;
5792 case glslang::EOpUnpackDouble2x32:
5793 libCall = spv::GLSLstd450UnpackDouble2x32;
5794 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005795#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005796
Rex Xu8ff43de2016-04-22 16:51:45 +08005797 case glslang::EOpPackInt2x32:
5798 case glslang::EOpUnpackInt2x32:
5799 case glslang::EOpPackUint2x32:
5800 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005801 case glslang::EOpPack16:
5802 case glslang::EOpPack32:
5803 case glslang::EOpPack64:
5804 case glslang::EOpUnpack32:
5805 case glslang::EOpUnpack16:
5806 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005807 case glslang::EOpPackInt2x16:
5808 case glslang::EOpUnpackInt2x16:
5809 case glslang::EOpPackUint2x16:
5810 case glslang::EOpUnpackUint2x16:
5811 case glslang::EOpPackInt4x16:
5812 case glslang::EOpUnpackInt4x16:
5813 case glslang::EOpPackUint4x16:
5814 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005815 case glslang::EOpPackFloat2x16:
5816 case glslang::EOpUnpackFloat2x16:
5817 unaryOp = spv::OpBitcast;
5818 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005819
John Kessenich140f3df2015-06-26 16:58:36 -06005820 case glslang::EOpDPdx:
5821 unaryOp = spv::OpDPdx;
5822 break;
5823 case glslang::EOpDPdy:
5824 unaryOp = spv::OpDPdy;
5825 break;
5826 case glslang::EOpFwidth:
5827 unaryOp = spv::OpFwidth;
5828 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005829
John Kessenich140f3df2015-06-26 16:58:36 -06005830 case glslang::EOpAny:
5831 unaryOp = spv::OpAny;
5832 break;
5833 case glslang::EOpAll:
5834 unaryOp = spv::OpAll;
5835 break;
5836
5837 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005838 if (isFloat)
5839 libCall = spv::GLSLstd450FAbs;
5840 else
5841 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005842 break;
5843 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005844 if (isFloat)
5845 libCall = spv::GLSLstd450FSign;
5846 else
5847 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
5849
John Kessenicha28f7a72019-08-06 07:00:58 -06005850#ifndef GLSLANG_WEB
5851 case glslang::EOpDPdxFine:
5852 unaryOp = spv::OpDPdxFine;
5853 break;
5854 case glslang::EOpDPdyFine:
5855 unaryOp = spv::OpDPdyFine;
5856 break;
5857 case glslang::EOpFwidthFine:
5858 unaryOp = spv::OpFwidthFine;
5859 break;
5860 case glslang::EOpDPdxCoarse:
5861 unaryOp = spv::OpDPdxCoarse;
5862 break;
5863 case glslang::EOpDPdyCoarse:
5864 unaryOp = spv::OpDPdyCoarse;
5865 break;
5866 case glslang::EOpFwidthCoarse:
5867 unaryOp = spv::OpFwidthCoarse;
5868 break;
5869 case glslang::EOpInterpolateAtCentroid:
5870 if (typeProxy == glslang::EbtFloat16)
5871 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5872 libCall = spv::GLSLstd450InterpolateAtCentroid;
5873 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005874 case glslang::EOpAtomicCounterIncrement:
5875 case glslang::EOpAtomicCounterDecrement:
5876 case glslang::EOpAtomicCounter:
5877 {
5878 // Handle all of the atomics in one place, in createAtomicOperation()
5879 std::vector<spv::Id> operands;
5880 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005881 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005882 }
5883
John Kessenichfc51d282015-08-19 13:34:18 -06005884 case glslang::EOpBitFieldReverse:
5885 unaryOp = spv::OpBitReverse;
5886 break;
5887 case glslang::EOpBitCount:
5888 unaryOp = spv::OpBitCount;
5889 break;
5890 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005891 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005892 break;
5893 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005894 if (isUnsigned)
5895 libCall = spv::GLSLstd450FindUMsb;
5896 else
5897 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005898 break;
5899
Ian Romanickb3bd4022019-01-21 08:57:25 -08005900 case glslang::EOpCountLeadingZeros:
5901 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5902 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5903 unaryOp = spv::OpUCountLeadingZerosINTEL;
5904 break;
5905
5906 case glslang::EOpCountTrailingZeros:
5907 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5908 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5909 unaryOp = spv::OpUCountTrailingZerosINTEL;
5910 break;
5911
Rex Xu574ab042016-04-14 16:53:07 +08005912 case glslang::EOpBallot:
5913 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005914 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005915 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005916 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005917 case glslang::EOpMinInvocations:
5918 case glslang::EOpMaxInvocations:
5919 case glslang::EOpAddInvocations:
5920 case glslang::EOpMinInvocationsNonUniform:
5921 case glslang::EOpMaxInvocationsNonUniform:
5922 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005923 case glslang::EOpMinInvocationsInclusiveScan:
5924 case glslang::EOpMaxInvocationsInclusiveScan:
5925 case glslang::EOpAddInvocationsInclusiveScan:
5926 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5927 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5928 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5929 case glslang::EOpMinInvocationsExclusiveScan:
5930 case glslang::EOpMaxInvocationsExclusiveScan:
5931 case glslang::EOpAddInvocationsExclusiveScan:
5932 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5933 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5934 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005935 {
5936 std::vector<spv::Id> operands;
5937 operands.push_back(operand);
5938 return createInvocationsOperation(op, typeId, operands, typeProxy);
5939 }
John Kessenich66011cb2018-03-06 16:12:04 -07005940 case glslang::EOpSubgroupAll:
5941 case glslang::EOpSubgroupAny:
5942 case glslang::EOpSubgroupAllEqual:
5943 case glslang::EOpSubgroupBroadcastFirst:
5944 case glslang::EOpSubgroupBallot:
5945 case glslang::EOpSubgroupInverseBallot:
5946 case glslang::EOpSubgroupBallotBitCount:
5947 case glslang::EOpSubgroupBallotInclusiveBitCount:
5948 case glslang::EOpSubgroupBallotExclusiveBitCount:
5949 case glslang::EOpSubgroupBallotFindLSB:
5950 case glslang::EOpSubgroupBallotFindMSB:
5951 case glslang::EOpSubgroupAdd:
5952 case glslang::EOpSubgroupMul:
5953 case glslang::EOpSubgroupMin:
5954 case glslang::EOpSubgroupMax:
5955 case glslang::EOpSubgroupAnd:
5956 case glslang::EOpSubgroupOr:
5957 case glslang::EOpSubgroupXor:
5958 case glslang::EOpSubgroupInclusiveAdd:
5959 case glslang::EOpSubgroupInclusiveMul:
5960 case glslang::EOpSubgroupInclusiveMin:
5961 case glslang::EOpSubgroupInclusiveMax:
5962 case glslang::EOpSubgroupInclusiveAnd:
5963 case glslang::EOpSubgroupInclusiveOr:
5964 case glslang::EOpSubgroupInclusiveXor:
5965 case glslang::EOpSubgroupExclusiveAdd:
5966 case glslang::EOpSubgroupExclusiveMul:
5967 case glslang::EOpSubgroupExclusiveMin:
5968 case glslang::EOpSubgroupExclusiveMax:
5969 case glslang::EOpSubgroupExclusiveAnd:
5970 case glslang::EOpSubgroupExclusiveOr:
5971 case glslang::EOpSubgroupExclusiveXor:
5972 case glslang::EOpSubgroupQuadSwapHorizontal:
5973 case glslang::EOpSubgroupQuadSwapVertical:
5974 case glslang::EOpSubgroupQuadSwapDiagonal: {
5975 std::vector<spv::Id> operands;
5976 operands.push_back(operand);
5977 return createSubgroupOperation(op, typeId, operands, typeProxy);
5978 }
Rex Xu9d93a232016-05-05 12:30:44 +08005979 case glslang::EOpMbcnt:
5980 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5981 libCall = spv::MbcntAMD;
5982 break;
5983
5984 case glslang::EOpCubeFaceIndex:
5985 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5986 libCall = spv::CubeFaceIndexAMD;
5987 break;
5988
5989 case glslang::EOpCubeFaceCoord:
5990 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5991 libCall = spv::CubeFaceCoordAMD;
5992 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005993 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005994 unaryOp = spv::OpGroupNonUniformPartitionNV;
5995 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005996 case glslang::EOpConstructReference:
5997 unaryOp = spv::OpBitcast;
5998 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005999#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006000
6001 case glslang::EOpCopyObject:
6002 unaryOp = spv::OpCopyObject;
6003 break;
6004
John Kessenich140f3df2015-06-26 16:58:36 -06006005 default:
6006 return 0;
6007 }
6008
6009 spv::Id id;
6010 if (libCall >= 0) {
6011 std::vector<spv::Id> args;
6012 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006013 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006014 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006015 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006016 }
John Kessenich140f3df2015-06-26 16:58:36 -06006017
John Kessenichb9197c82019-08-11 07:41:45 -06006018 decorations.addNoContraction(builder, id);
6019 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006020 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006021}
6022
John Kessenich7a53f762016-01-20 11:19:27 -07006023// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006024spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6025 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006026{
6027 // Handle unary operations vector by vector.
6028 // The result type is the same type as the original type.
6029 // The algorithm is to:
6030 // - break the matrix into vectors
6031 // - apply the operation to each vector
6032 // - make a matrix out the vector results
6033
6034 // get the types sorted out
6035 int numCols = builder.getNumColumns(operand);
6036 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006037 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6038 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006039 std::vector<spv::Id> results;
6040
6041 // do each vector op
6042 for (int c = 0; c < numCols; ++c) {
6043 std::vector<unsigned int> indexes;
6044 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006045 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6046 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006047 decorations.addNoContraction(builder, destVec);
6048 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006049 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006050 }
6051
6052 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006053 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006054 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006055 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006056}
6057
John Kessenichad7645f2018-06-04 19:11:25 -06006058// For converting integers where both the bitwidth and the signedness could
6059// change, but only do the width change here. The caller is still responsible
6060// for the signedness conversion.
6061spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006062{
John Kessenichad7645f2018-06-04 19:11:25 -06006063 // Get the result type width, based on the type to convert to.
6064 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006065 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006066 case glslang::EOpConvInt16ToUint8:
6067 case glslang::EOpConvIntToUint8:
6068 case glslang::EOpConvInt64ToUint8:
6069 case glslang::EOpConvUint16ToInt8:
6070 case glslang::EOpConvUintToInt8:
6071 case glslang::EOpConvUint64ToInt8:
6072 width = 8;
6073 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006074 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006075 case glslang::EOpConvIntToUint16:
6076 case glslang::EOpConvInt64ToUint16:
6077 case glslang::EOpConvUint8ToInt16:
6078 case glslang::EOpConvUintToInt16:
6079 case glslang::EOpConvUint64ToInt16:
6080 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006081 break;
6082 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006083 case glslang::EOpConvInt16ToUint:
6084 case glslang::EOpConvInt64ToUint:
6085 case glslang::EOpConvUint8ToInt:
6086 case glslang::EOpConvUint16ToInt:
6087 case glslang::EOpConvUint64ToInt:
6088 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006089 break;
6090 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006091 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006092 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006093 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006094 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006095 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006096 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006097 break;
6098
6099 default:
6100 assert(false && "Default missing");
6101 break;
6102 }
6103
John Kessenichad7645f2018-06-04 19:11:25 -06006104 // Get the conversion operation and result type,
6105 // based on the target width, but the source type.
6106 spv::Id type = spv::NoType;
6107 spv::Op convOp = spv::OpNop;
6108 switch(op) {
6109 case glslang::EOpConvInt8ToUint16:
6110 case glslang::EOpConvInt8ToUint:
6111 case glslang::EOpConvInt8ToUint64:
6112 case glslang::EOpConvInt16ToUint8:
6113 case glslang::EOpConvInt16ToUint:
6114 case glslang::EOpConvInt16ToUint64:
6115 case glslang::EOpConvIntToUint8:
6116 case glslang::EOpConvIntToUint16:
6117 case glslang::EOpConvIntToUint64:
6118 case glslang::EOpConvInt64ToUint8:
6119 case glslang::EOpConvInt64ToUint16:
6120 case glslang::EOpConvInt64ToUint:
6121 convOp = spv::OpSConvert;
6122 type = builder.makeIntType(width);
6123 break;
6124 default:
6125 convOp = spv::OpUConvert;
6126 type = builder.makeUintType(width);
6127 break;
6128 }
6129
John Kessenich66011cb2018-03-06 16:12:04 -07006130 if (vectorSize > 0)
6131 type = builder.makeVectorType(type, vectorSize);
6132
John Kessenichad7645f2018-06-04 19:11:25 -06006133 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006134}
6135
John Kessenichead86222018-03-28 18:01:20 -06006136spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6137 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006138{
6139 spv::Op convOp = spv::OpNop;
6140 spv::Id zero = 0;
6141 spv::Id one = 0;
6142
6143 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6144
6145 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006146 case glslang::EOpConvIntToBool:
6147 case glslang::EOpConvUintToBool:
6148 zero = builder.makeUintConstant(0);
6149 zero = makeSmearedConstant(zero, vectorSize);
6150 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006151 case glslang::EOpConvFloatToBool:
6152 zero = builder.makeFloatConstant(0.0F);
6153 zero = makeSmearedConstant(zero, vectorSize);
6154 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006155 case glslang::EOpConvBoolToFloat:
6156 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006157 zero = builder.makeFloatConstant(0.0F);
6158 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006159 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006160
John Kessenich140f3df2015-06-26 16:58:36 -06006161 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006162 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006163#ifndef GLSLANG_WEB
6164 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006165 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006166 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006167 } else
6168#endif
6169 {
6170 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006171 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006172 }
Rex Xucabbb782017-03-24 13:41:14 +08006173
John Kessenich140f3df2015-06-26 16:58:36 -06006174 convOp = spv::OpSelect;
6175 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006176
John Kessenich140f3df2015-06-26 16:58:36 -06006177 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006178 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006179#ifndef GLSLANG_WEB
6180 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006181 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006182 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006183 } else
6184#endif
6185 {
6186 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006187 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006188 }
Rex Xucabbb782017-03-24 13:41:14 +08006189
John Kessenich140f3df2015-06-26 16:58:36 -06006190 convOp = spv::OpSelect;
6191 break;
6192
John Kessenich66011cb2018-03-06 16:12:04 -07006193 case glslang::EOpConvInt8ToFloat16:
6194 case glslang::EOpConvInt8ToFloat:
6195 case glslang::EOpConvInt8ToDouble:
6196 case glslang::EOpConvInt16ToFloat16:
6197 case glslang::EOpConvInt16ToFloat:
6198 case glslang::EOpConvInt16ToDouble:
6199 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006200 case glslang::EOpConvIntToFloat:
6201 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006202 case glslang::EOpConvInt64ToFloat:
6203 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006204 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006205 convOp = spv::OpConvertSToF;
6206 break;
6207
John Kessenich66011cb2018-03-06 16:12:04 -07006208 case glslang::EOpConvUint8ToFloat16:
6209 case glslang::EOpConvUint8ToFloat:
6210 case glslang::EOpConvUint8ToDouble:
6211 case glslang::EOpConvUint16ToFloat16:
6212 case glslang::EOpConvUint16ToFloat:
6213 case glslang::EOpConvUint16ToDouble:
6214 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006215 case glslang::EOpConvUintToFloat:
6216 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006217 case glslang::EOpConvUint64ToFloat:
6218 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006219 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006220 convOp = spv::OpConvertUToF;
6221 break;
6222
John Kessenich66011cb2018-03-06 16:12:04 -07006223 case glslang::EOpConvFloat16ToInt8:
6224 case glslang::EOpConvFloatToInt8:
6225 case glslang::EOpConvDoubleToInt8:
6226 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006227 case glslang::EOpConvFloatToInt16:
6228 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006229 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006230 case glslang::EOpConvFloatToInt:
6231 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006232 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006233 case glslang::EOpConvFloatToInt64:
6234 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006235 convOp = spv::OpConvertFToS;
6236 break;
6237
John Kessenich66011cb2018-03-06 16:12:04 -07006238 case glslang::EOpConvUint8ToInt8:
6239 case glslang::EOpConvInt8ToUint8:
6240 case glslang::EOpConvUint16ToInt16:
6241 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006242 case glslang::EOpConvUintToInt:
6243 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006244 case glslang::EOpConvUint64ToInt64:
6245 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006246 if (builder.isInSpecConstCodeGenMode()) {
6247 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006248#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006249 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6250 zero = builder.makeUint8Constant(0);
6251 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006252 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006253 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6254 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006255 } else
6256#endif
6257 {
Rex Xucabbb782017-03-24 13:41:14 +08006258 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006259 }
qining189b2032016-04-12 23:16:20 -04006260 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006261 // Use OpIAdd, instead of OpBitcast to do the conversion when
6262 // generating for OpSpecConstantOp instruction.
6263 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6264 }
6265 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006266 convOp = spv::OpBitcast;
6267 break;
6268
John Kessenich66011cb2018-03-06 16:12:04 -07006269 case glslang::EOpConvFloat16ToUint8:
6270 case glslang::EOpConvFloatToUint8:
6271 case glslang::EOpConvDoubleToUint8:
6272 case glslang::EOpConvFloat16ToUint16:
6273 case glslang::EOpConvFloatToUint16:
6274 case glslang::EOpConvDoubleToUint16:
6275 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006276 case glslang::EOpConvFloatToUint:
6277 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006278 case glslang::EOpConvFloatToUint64:
6279 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006280 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006281 convOp = spv::OpConvertFToU;
6282 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006283
John Kessenich39697cd2019-08-08 10:35:51 -06006284#ifndef GLSLANG_WEB
6285 case glslang::EOpConvInt8ToBool:
6286 case glslang::EOpConvUint8ToBool:
6287 zero = builder.makeUint8Constant(0);
6288 zero = makeSmearedConstant(zero, vectorSize);
6289 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6290 case glslang::EOpConvInt16ToBool:
6291 case glslang::EOpConvUint16ToBool:
6292 zero = builder.makeUint16Constant(0);
6293 zero = makeSmearedConstant(zero, vectorSize);
6294 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6295 case glslang::EOpConvInt64ToBool:
6296 case glslang::EOpConvUint64ToBool:
6297 zero = builder.makeUint64Constant(0);
6298 zero = makeSmearedConstant(zero, vectorSize);
6299 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6300 case glslang::EOpConvDoubleToBool:
6301 zero = builder.makeDoubleConstant(0.0);
6302 zero = makeSmearedConstant(zero, vectorSize);
6303 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6304 case glslang::EOpConvFloat16ToBool:
6305 zero = builder.makeFloat16Constant(0.0F);
6306 zero = makeSmearedConstant(zero, vectorSize);
6307 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6308 case glslang::EOpConvBoolToDouble:
6309 convOp = spv::OpSelect;
6310 zero = builder.makeDoubleConstant(0.0);
6311 one = builder.makeDoubleConstant(1.0);
6312 break;
6313 case glslang::EOpConvBoolToFloat16:
6314 convOp = spv::OpSelect;
6315 zero = builder.makeFloat16Constant(0.0F);
6316 one = builder.makeFloat16Constant(1.0F);
6317 break;
6318 case glslang::EOpConvBoolToInt8:
6319 zero = builder.makeInt8Constant(0);
6320 one = builder.makeInt8Constant(1);
6321 convOp = spv::OpSelect;
6322 break;
6323 case glslang::EOpConvBoolToUint8:
6324 zero = builder.makeUint8Constant(0);
6325 one = builder.makeUint8Constant(1);
6326 convOp = spv::OpSelect;
6327 break;
6328 case glslang::EOpConvBoolToInt16:
6329 zero = builder.makeInt16Constant(0);
6330 one = builder.makeInt16Constant(1);
6331 convOp = spv::OpSelect;
6332 break;
6333 case glslang::EOpConvBoolToUint16:
6334 zero = builder.makeUint16Constant(0);
6335 one = builder.makeUint16Constant(1);
6336 convOp = spv::OpSelect;
6337 break;
6338 case glslang::EOpConvDoubleToFloat:
6339 case glslang::EOpConvFloatToDouble:
6340 case glslang::EOpConvDoubleToFloat16:
6341 case glslang::EOpConvFloat16ToDouble:
6342 case glslang::EOpConvFloatToFloat16:
6343 case glslang::EOpConvFloat16ToFloat:
6344 convOp = spv::OpFConvert;
6345 if (builder.isMatrixType(destType))
6346 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6347 break;
6348
John Kessenich66011cb2018-03-06 16:12:04 -07006349 case glslang::EOpConvInt8ToInt16:
6350 case glslang::EOpConvInt8ToInt:
6351 case glslang::EOpConvInt8ToInt64:
6352 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006353 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006354 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006355 case glslang::EOpConvIntToInt8:
6356 case glslang::EOpConvIntToInt16:
6357 case glslang::EOpConvIntToInt64:
6358 case glslang::EOpConvInt64ToInt8:
6359 case glslang::EOpConvInt64ToInt16:
6360 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006361 convOp = spv::OpSConvert;
6362 break;
6363
John Kessenich66011cb2018-03-06 16:12:04 -07006364 case glslang::EOpConvUint8ToUint16:
6365 case glslang::EOpConvUint8ToUint:
6366 case glslang::EOpConvUint8ToUint64:
6367 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006368 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006369 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006370 case glslang::EOpConvUintToUint8:
6371 case glslang::EOpConvUintToUint16:
6372 case glslang::EOpConvUintToUint64:
6373 case glslang::EOpConvUint64ToUint8:
6374 case glslang::EOpConvUint64ToUint16:
6375 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006376 convOp = spv::OpUConvert;
6377 break;
6378
John Kessenich66011cb2018-03-06 16:12:04 -07006379 case glslang::EOpConvInt8ToUint16:
6380 case glslang::EOpConvInt8ToUint:
6381 case glslang::EOpConvInt8ToUint64:
6382 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006383 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006384 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006385 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006386 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006387 case glslang::EOpConvIntToUint64:
6388 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006389 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006390 case glslang::EOpConvInt64ToUint:
6391 case glslang::EOpConvUint8ToInt16:
6392 case glslang::EOpConvUint8ToInt:
6393 case glslang::EOpConvUint8ToInt64:
6394 case glslang::EOpConvUint16ToInt8:
6395 case glslang::EOpConvUint16ToInt:
6396 case glslang::EOpConvUint16ToInt64:
6397 case glslang::EOpConvUintToInt8:
6398 case glslang::EOpConvUintToInt16:
6399 case glslang::EOpConvUintToInt64:
6400 case glslang::EOpConvUint64ToInt8:
6401 case glslang::EOpConvUint64ToInt16:
6402 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006403 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006404 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006405
6406 if (builder.isInSpecConstCodeGenMode()) {
6407 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006408 switch(op) {
6409 case glslang::EOpConvInt16ToUint8:
6410 case glslang::EOpConvIntToUint8:
6411 case glslang::EOpConvInt64ToUint8:
6412 case glslang::EOpConvUint16ToInt8:
6413 case glslang::EOpConvUintToInt8:
6414 case glslang::EOpConvUint64ToInt8:
6415 zero = builder.makeUint8Constant(0);
6416 break;
6417 case glslang::EOpConvInt8ToUint16:
6418 case glslang::EOpConvIntToUint16:
6419 case glslang::EOpConvInt64ToUint16:
6420 case glslang::EOpConvUint8ToInt16:
6421 case glslang::EOpConvUintToInt16:
6422 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006423 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006424 break;
6425 case glslang::EOpConvInt8ToUint:
6426 case glslang::EOpConvInt16ToUint:
6427 case glslang::EOpConvInt64ToUint:
6428 case glslang::EOpConvUint8ToInt:
6429 case glslang::EOpConvUint16ToInt:
6430 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006431 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006432 break;
6433 case glslang::EOpConvInt8ToUint64:
6434 case glslang::EOpConvInt16ToUint64:
6435 case glslang::EOpConvIntToUint64:
6436 case glslang::EOpConvUint8ToInt64:
6437 case glslang::EOpConvUint16ToInt64:
6438 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006439 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006440 break;
6441 default:
6442 assert(false && "Default missing");
6443 break;
6444 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006445 zero = makeSmearedConstant(zero, vectorSize);
6446 // Use OpIAdd, instead of OpBitcast to do the conversion when
6447 // generating for OpSpecConstantOp instruction.
6448 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6449 }
6450 // For normal run-time conversion instruction, use OpBitcast.
6451 convOp = spv::OpBitcast;
6452 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006453 case glslang::EOpConvUint64ToPtr:
6454 convOp = spv::OpConvertUToPtr;
6455 break;
6456 case glslang::EOpConvPtrToUint64:
6457 convOp = spv::OpConvertPtrToU;
6458 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006459 case glslang::EOpConvPtrToUvec2:
6460 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006461 if (builder.isVector(operand))
6462 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6463 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006464 convOp = spv::OpBitcast;
6465 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006466#endif
6467
John Kessenich140f3df2015-06-26 16:58:36 -06006468 default:
6469 break;
6470 }
6471
6472 spv::Id result = 0;
6473 if (convOp == spv::OpNop)
6474 return result;
6475
6476 if (convOp == spv::OpSelect) {
6477 zero = makeSmearedConstant(zero, vectorSize);
6478 one = makeSmearedConstant(one, vectorSize);
6479 result = builder.createTriOp(convOp, destType, operand, one, zero);
6480 } else
6481 result = builder.createUnaryOp(convOp, destType, operand);
6482
John Kessenichead86222018-03-28 18:01:20 -06006483 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006484 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006485 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006486}
6487
6488spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6489{
6490 if (vectorSize == 0)
6491 return constant;
6492
6493 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6494 std::vector<spv::Id> components;
6495 for (int c = 0; c < vectorSize; ++c)
6496 components.push_back(constant);
6497 return builder.makeCompositeConstant(vectorTypeId, components);
6498}
6499
John Kessenich426394d2015-07-23 10:22:48 -06006500// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006501spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6502 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6503 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006504{
6505 spv::Op opCode = spv::OpNop;
6506
6507 switch (op) {
6508 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006509 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006510 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006511 opCode = spv::OpAtomicIAdd;
6512 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006513 case glslang::EOpAtomicCounterSubtract:
6514 opCode = spv::OpAtomicISub;
6515 break;
John Kessenich426394d2015-07-23 10:22:48 -06006516 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006517 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006518 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006519 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6520 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006521 break;
6522 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006523 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006524 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006525 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6526 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006527 break;
6528 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006529 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006530 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006531 opCode = spv::OpAtomicAnd;
6532 break;
6533 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006534 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006535 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006536 opCode = spv::OpAtomicOr;
6537 break;
6538 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006539 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006540 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006541 opCode = spv::OpAtomicXor;
6542 break;
6543 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006544 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006545 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006546 opCode = spv::OpAtomicExchange;
6547 break;
6548 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006549 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006550 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006551 opCode = spv::OpAtomicCompareExchange;
6552 break;
6553 case glslang::EOpAtomicCounterIncrement:
6554 opCode = spv::OpAtomicIIncrement;
6555 break;
6556 case glslang::EOpAtomicCounterDecrement:
6557 opCode = spv::OpAtomicIDecrement;
6558 break;
6559 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006560 case glslang::EOpImageAtomicLoad:
6561 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006562 opCode = spv::OpAtomicLoad;
6563 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006564 case glslang::EOpAtomicStore:
6565 case glslang::EOpImageAtomicStore:
6566 opCode = spv::OpAtomicStore;
6567 break;
John Kessenich426394d2015-07-23 10:22:48 -06006568 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006569 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006570 break;
6571 }
6572
Rex Xue8fe8b02017-09-26 15:42:56 +08006573 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6574 builder.addCapability(spv::CapabilityInt64Atomics);
6575
John Kessenich426394d2015-07-23 10:22:48 -06006576 // Sort out the operands
6577 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006578 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006579 // - compare-exchange swaps the value and comparator
6580 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006581 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006582 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6583 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6584 spv::Id scopeId;
6585 if (glslangIntermediate->usingVulkanMemoryModel()) {
6586 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6587 } else {
6588 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6589 }
6590 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006591 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6592 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006593 spv::MemorySemanticsVolatileMask :
6594 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006595 spv::Id semanticsId2 = semanticsId;
6596
6597 pointerId = operands[0];
6598 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6599 // no additional operands
6600 } else if (opCode == spv::OpAtomicCompareExchange) {
6601 compareId = operands[1];
6602 valueId = operands[2];
6603 if (operands.size() > 3) {
6604 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006605 semanticsId = builder.makeUintConstant(
6606 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6607 semanticsId2 = builder.makeUintConstant(
6608 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006609 }
6610 } else if (opCode == spv::OpAtomicLoad) {
6611 if (operands.size() > 1) {
6612 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006613 semanticsId = builder.makeUintConstant(
6614 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006615 }
6616 } else {
6617 // atomic store or RMW
6618 valueId = operands[1];
6619 if (operands.size() > 2) {
6620 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006621 semanticsId = builder.makeUintConstant
6622 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006623 }
Rex Xu04db3f52015-09-16 11:44:02 +08006624 }
John Kessenich426394d2015-07-23 10:22:48 -06006625
Jeff Bolz36831c92018-09-05 10:11:41 -05006626 // Check for capabilities
6627 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006628 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6629 spv::MemorySemanticsMakeVisibleKHRMask |
6630 spv::MemorySemanticsOutputMemoryKHRMask |
6631 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006632 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6633 }
John Kessenich426394d2015-07-23 10:22:48 -06006634
Jeff Bolz36831c92018-09-05 10:11:41 -05006635 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6636 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6637 }
John Kessenich48d6e792017-10-06 21:21:48 -06006638
Jeff Bolz36831c92018-09-05 10:11:41 -05006639 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6640 spvAtomicOperands.push_back(pointerId);
6641 spvAtomicOperands.push_back(scopeId);
6642 spvAtomicOperands.push_back(semanticsId);
6643 if (opCode == spv::OpAtomicCompareExchange) {
6644 spvAtomicOperands.push_back(semanticsId2);
6645 spvAtomicOperands.push_back(valueId);
6646 spvAtomicOperands.push_back(compareId);
6647 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6648 spvAtomicOperands.push_back(valueId);
6649 }
John Kessenich48d6e792017-10-06 21:21:48 -06006650
Jeff Bolz36831c92018-09-05 10:11:41 -05006651 if (opCode == spv::OpAtomicStore) {
6652 builder.createNoResultOp(opCode, spvAtomicOperands);
6653 return 0;
6654 } else {
6655 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6656
6657 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6658 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6659 if (op == glslang::EOpAtomicCounterDecrement)
6660 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6661
6662 return resultId;
6663 }
John Kessenich426394d2015-07-23 10:22:48 -06006664}
6665
John Kessenich91cef522016-05-05 16:45:40 -06006666// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006667spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6668 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006669{
John Kessenich66011cb2018-03-06 16:12:04 -07006670 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6671 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006672
Rex Xu51596642016-09-21 18:56:12 +08006673 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006674 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006675 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6676
chaocf200da82016-12-20 12:44:35 -08006677 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6678 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006679 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6680 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006681 } else if (op == glslang::EOpAnyInvocation ||
6682 op == glslang::EOpAllInvocations ||
6683 op == glslang::EOpAllInvocationsEqual) {
6684 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6685 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006686 } else {
6687 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006688 if (op == glslang::EOpMinInvocationsNonUniform ||
6689 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006690 op == glslang::EOpAddInvocationsNonUniform ||
6691 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6692 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6693 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6694 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6695 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6696 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006697 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006698
Rex Xu430ef402016-10-14 17:22:23 +08006699 switch (op) {
6700 case glslang::EOpMinInvocations:
6701 case glslang::EOpMaxInvocations:
6702 case glslang::EOpAddInvocations:
6703 case glslang::EOpMinInvocationsNonUniform:
6704 case glslang::EOpMaxInvocationsNonUniform:
6705 case glslang::EOpAddInvocationsNonUniform:
6706 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006707 break;
6708 case glslang::EOpMinInvocationsInclusiveScan:
6709 case glslang::EOpMaxInvocationsInclusiveScan:
6710 case glslang::EOpAddInvocationsInclusiveScan:
6711 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6712 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6713 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6714 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006715 break;
6716 case glslang::EOpMinInvocationsExclusiveScan:
6717 case glslang::EOpMaxInvocationsExclusiveScan:
6718 case glslang::EOpAddInvocationsExclusiveScan:
6719 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6720 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6721 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6722 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006723 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006724 default:
6725 break;
Rex Xu430ef402016-10-14 17:22:23 +08006726 }
John Kessenich149afc32018-08-14 13:31:43 -06006727 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6728 spvGroupOperands.push_back(scope);
6729 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006730 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006731 spvGroupOperands.push_back(groupOp);
6732 }
Rex Xu51596642016-09-21 18:56:12 +08006733 }
6734
John Kessenich149afc32018-08-14 13:31:43 -06006735 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6736 spv::IdImmediate op = { true, *opIt };
6737 spvGroupOperands.push_back(op);
6738 }
John Kessenich91cef522016-05-05 16:45:40 -06006739
6740 switch (op) {
6741 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006742 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006743 break;
John Kessenich91cef522016-05-05 16:45:40 -06006744 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006745 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006746 break;
John Kessenich91cef522016-05-05 16:45:40 -06006747 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006748 opCode = spv::OpSubgroupAllEqualKHR;
6749 break;
Rex Xu51596642016-09-21 18:56:12 +08006750 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006751 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006752 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006753 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006754 break;
6755 case glslang::EOpReadFirstInvocation:
6756 opCode = spv::OpSubgroupFirstInvocationKHR;
6757 break;
6758 case glslang::EOpBallot:
6759 {
6760 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6761 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6762 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6763 //
6764 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6765 //
6766 spv::Id uintType = builder.makeUintType(32);
6767 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6768 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6769
6770 std::vector<spv::Id> components;
6771 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6772 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6773
6774 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6775 return builder.createUnaryOp(spv::OpBitcast, typeId,
6776 builder.createCompositeConstruct(uvec2Type, components));
6777 }
6778
Rex Xu9d93a232016-05-05 12:30:44 +08006779 case glslang::EOpMinInvocations:
6780 case glslang::EOpMaxInvocations:
6781 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006782 case glslang::EOpMinInvocationsInclusiveScan:
6783 case glslang::EOpMaxInvocationsInclusiveScan:
6784 case glslang::EOpAddInvocationsInclusiveScan:
6785 case glslang::EOpMinInvocationsExclusiveScan:
6786 case glslang::EOpMaxInvocationsExclusiveScan:
6787 case glslang::EOpAddInvocationsExclusiveScan:
6788 if (op == glslang::EOpMinInvocations ||
6789 op == glslang::EOpMinInvocationsInclusiveScan ||
6790 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006791 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006792 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006793 else {
6794 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006795 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006796 else
Rex Xu51596642016-09-21 18:56:12 +08006797 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006798 }
Rex Xu430ef402016-10-14 17:22:23 +08006799 } else if (op == glslang::EOpMaxInvocations ||
6800 op == glslang::EOpMaxInvocationsInclusiveScan ||
6801 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006802 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006803 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006804 else {
6805 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006806 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006807 else
Rex Xu51596642016-09-21 18:56:12 +08006808 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006809 }
6810 } else {
6811 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006812 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006813 else
Rex Xu51596642016-09-21 18:56:12 +08006814 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006815 }
6816
Rex Xu2bbbe062016-08-23 15:41:05 +08006817 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006818 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006819
6820 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006821 case glslang::EOpMinInvocationsNonUniform:
6822 case glslang::EOpMaxInvocationsNonUniform:
6823 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006824 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6825 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6826 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6827 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6828 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6829 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6830 if (op == glslang::EOpMinInvocationsNonUniform ||
6831 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6832 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006833 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006834 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006835 else {
6836 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006837 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006838 else
Rex Xu51596642016-09-21 18:56:12 +08006839 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006840 }
6841 }
Rex Xu430ef402016-10-14 17:22:23 +08006842 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6843 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6844 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006845 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006846 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006847 else {
6848 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006849 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006850 else
Rex Xu51596642016-09-21 18:56:12 +08006851 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006852 }
6853 }
6854 else {
6855 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006856 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006857 else
Rex Xu51596642016-09-21 18:56:12 +08006858 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006859 }
6860
Rex Xu2bbbe062016-08-23 15:41:05 +08006861 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006862 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006863
6864 break;
John Kessenich91cef522016-05-05 16:45:40 -06006865 default:
6866 logger->missingFunctionality("invocation operation");
6867 return spv::NoResult;
6868 }
Rex Xu51596642016-09-21 18:56:12 +08006869
6870 assert(opCode != spv::OpNop);
6871 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006872}
6873
Rex Xu2bbbe062016-08-23 15:41:05 +08006874// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006875spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6876 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006877{
6878 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6879 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006880 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006881 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07006882 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
6883 op == spv::OpGroupSMinNonUniformAMD ||
6884 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
6885 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006886 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6887
6888 // Handle group invocation operations scalar by scalar.
6889 // The result type is the same type as the original type.
6890 // The algorithm is to:
6891 // - break the vector into scalars
6892 // - apply the operation to each scalar
6893 // - make a vector out the scalar results
6894
6895 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006896 int numComponents = builder.getNumComponents(operands[0]);
6897 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006898 std::vector<spv::Id> results;
6899
6900 // do each scalar op
6901 for (int comp = 0; comp < numComponents; ++comp) {
6902 std::vector<unsigned int> indexes;
6903 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006904 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6905 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006906 if (op == spv::OpSubgroupReadInvocationKHR) {
6907 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006908 spv::IdImmediate operand = { true, operands[1] };
6909 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006910 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006911 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6912 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006913 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006914 spv::IdImmediate operand = { true, operands[1] };
6915 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006916 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006917 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6918 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006919 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006920 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006921 spvGroupOperands.push_back(scalar);
6922 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006923
Rex Xub7072052016-09-26 15:53:40 +08006924 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006925 }
6926
6927 // put the pieces together
6928 return builder.createCompositeConstruct(typeId, results);
6929}
Rex Xu2bbbe062016-08-23 15:41:05 +08006930
John Kessenich66011cb2018-03-06 16:12:04 -07006931// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006932spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6933 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006934{
6935 // Add the required capabilities.
6936 switch (op) {
6937 case glslang::EOpSubgroupElect:
6938 builder.addCapability(spv::CapabilityGroupNonUniform);
6939 break;
6940 case glslang::EOpSubgroupAll:
6941 case glslang::EOpSubgroupAny:
6942 case glslang::EOpSubgroupAllEqual:
6943 builder.addCapability(spv::CapabilityGroupNonUniform);
6944 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6945 break;
6946 case glslang::EOpSubgroupBroadcast:
6947 case glslang::EOpSubgroupBroadcastFirst:
6948 case glslang::EOpSubgroupBallot:
6949 case glslang::EOpSubgroupInverseBallot:
6950 case glslang::EOpSubgroupBallotBitExtract:
6951 case glslang::EOpSubgroupBallotBitCount:
6952 case glslang::EOpSubgroupBallotInclusiveBitCount:
6953 case glslang::EOpSubgroupBallotExclusiveBitCount:
6954 case glslang::EOpSubgroupBallotFindLSB:
6955 case glslang::EOpSubgroupBallotFindMSB:
6956 builder.addCapability(spv::CapabilityGroupNonUniform);
6957 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6958 break;
6959 case glslang::EOpSubgroupShuffle:
6960 case glslang::EOpSubgroupShuffleXor:
6961 builder.addCapability(spv::CapabilityGroupNonUniform);
6962 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6963 break;
6964 case glslang::EOpSubgroupShuffleUp:
6965 case glslang::EOpSubgroupShuffleDown:
6966 builder.addCapability(spv::CapabilityGroupNonUniform);
6967 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6968 break;
6969 case glslang::EOpSubgroupAdd:
6970 case glslang::EOpSubgroupMul:
6971 case glslang::EOpSubgroupMin:
6972 case glslang::EOpSubgroupMax:
6973 case glslang::EOpSubgroupAnd:
6974 case glslang::EOpSubgroupOr:
6975 case glslang::EOpSubgroupXor:
6976 case glslang::EOpSubgroupInclusiveAdd:
6977 case glslang::EOpSubgroupInclusiveMul:
6978 case glslang::EOpSubgroupInclusiveMin:
6979 case glslang::EOpSubgroupInclusiveMax:
6980 case glslang::EOpSubgroupInclusiveAnd:
6981 case glslang::EOpSubgroupInclusiveOr:
6982 case glslang::EOpSubgroupInclusiveXor:
6983 case glslang::EOpSubgroupExclusiveAdd:
6984 case glslang::EOpSubgroupExclusiveMul:
6985 case glslang::EOpSubgroupExclusiveMin:
6986 case glslang::EOpSubgroupExclusiveMax:
6987 case glslang::EOpSubgroupExclusiveAnd:
6988 case glslang::EOpSubgroupExclusiveOr:
6989 case glslang::EOpSubgroupExclusiveXor:
6990 builder.addCapability(spv::CapabilityGroupNonUniform);
6991 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6992 break;
6993 case glslang::EOpSubgroupClusteredAdd:
6994 case glslang::EOpSubgroupClusteredMul:
6995 case glslang::EOpSubgroupClusteredMin:
6996 case glslang::EOpSubgroupClusteredMax:
6997 case glslang::EOpSubgroupClusteredAnd:
6998 case glslang::EOpSubgroupClusteredOr:
6999 case glslang::EOpSubgroupClusteredXor:
7000 builder.addCapability(spv::CapabilityGroupNonUniform);
7001 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7002 break;
7003 case glslang::EOpSubgroupQuadBroadcast:
7004 case glslang::EOpSubgroupQuadSwapHorizontal:
7005 case glslang::EOpSubgroupQuadSwapVertical:
7006 case glslang::EOpSubgroupQuadSwapDiagonal:
7007 builder.addCapability(spv::CapabilityGroupNonUniform);
7008 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7009 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007010 case glslang::EOpSubgroupPartitionedAdd:
7011 case glslang::EOpSubgroupPartitionedMul:
7012 case glslang::EOpSubgroupPartitionedMin:
7013 case glslang::EOpSubgroupPartitionedMax:
7014 case glslang::EOpSubgroupPartitionedAnd:
7015 case glslang::EOpSubgroupPartitionedOr:
7016 case glslang::EOpSubgroupPartitionedXor:
7017 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7018 case glslang::EOpSubgroupPartitionedInclusiveMul:
7019 case glslang::EOpSubgroupPartitionedInclusiveMin:
7020 case glslang::EOpSubgroupPartitionedInclusiveMax:
7021 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7022 case glslang::EOpSubgroupPartitionedInclusiveOr:
7023 case glslang::EOpSubgroupPartitionedInclusiveXor:
7024 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7025 case glslang::EOpSubgroupPartitionedExclusiveMul:
7026 case glslang::EOpSubgroupPartitionedExclusiveMin:
7027 case glslang::EOpSubgroupPartitionedExclusiveMax:
7028 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7029 case glslang::EOpSubgroupPartitionedExclusiveOr:
7030 case glslang::EOpSubgroupPartitionedExclusiveXor:
7031 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7032 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7033 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007034 default: assert(0 && "Unhandled subgroup operation!");
7035 }
7036
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007037
7038 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7039 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007040 const bool isBool = typeProxy == glslang::EbtBool;
7041
7042 spv::Op opCode = spv::OpNop;
7043
7044 // Figure out which opcode to use.
7045 switch (op) {
7046 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7047 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7048 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7049 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7050 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7051 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7052 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7053 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7054 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7055 case glslang::EOpSubgroupBallotBitCount:
7056 case glslang::EOpSubgroupBallotInclusiveBitCount:
7057 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7058 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7059 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7060 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7061 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7062 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7063 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7064 case glslang::EOpSubgroupAdd:
7065 case glslang::EOpSubgroupInclusiveAdd:
7066 case glslang::EOpSubgroupExclusiveAdd:
7067 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007068 case glslang::EOpSubgroupPartitionedAdd:
7069 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7070 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007071 if (isFloat) {
7072 opCode = spv::OpGroupNonUniformFAdd;
7073 } else {
7074 opCode = spv::OpGroupNonUniformIAdd;
7075 }
7076 break;
7077 case glslang::EOpSubgroupMul:
7078 case glslang::EOpSubgroupInclusiveMul:
7079 case glslang::EOpSubgroupExclusiveMul:
7080 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007081 case glslang::EOpSubgroupPartitionedMul:
7082 case glslang::EOpSubgroupPartitionedInclusiveMul:
7083 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007084 if (isFloat) {
7085 opCode = spv::OpGroupNonUniformFMul;
7086 } else {
7087 opCode = spv::OpGroupNonUniformIMul;
7088 }
7089 break;
7090 case glslang::EOpSubgroupMin:
7091 case glslang::EOpSubgroupInclusiveMin:
7092 case glslang::EOpSubgroupExclusiveMin:
7093 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007094 case glslang::EOpSubgroupPartitionedMin:
7095 case glslang::EOpSubgroupPartitionedInclusiveMin:
7096 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007097 if (isFloat) {
7098 opCode = spv::OpGroupNonUniformFMin;
7099 } else if (isUnsigned) {
7100 opCode = spv::OpGroupNonUniformUMin;
7101 } else {
7102 opCode = spv::OpGroupNonUniformSMin;
7103 }
7104 break;
7105 case glslang::EOpSubgroupMax:
7106 case glslang::EOpSubgroupInclusiveMax:
7107 case glslang::EOpSubgroupExclusiveMax:
7108 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007109 case glslang::EOpSubgroupPartitionedMax:
7110 case glslang::EOpSubgroupPartitionedInclusiveMax:
7111 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007112 if (isFloat) {
7113 opCode = spv::OpGroupNonUniformFMax;
7114 } else if (isUnsigned) {
7115 opCode = spv::OpGroupNonUniformUMax;
7116 } else {
7117 opCode = spv::OpGroupNonUniformSMax;
7118 }
7119 break;
7120 case glslang::EOpSubgroupAnd:
7121 case glslang::EOpSubgroupInclusiveAnd:
7122 case glslang::EOpSubgroupExclusiveAnd:
7123 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007124 case glslang::EOpSubgroupPartitionedAnd:
7125 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7126 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007127 if (isBool) {
7128 opCode = spv::OpGroupNonUniformLogicalAnd;
7129 } else {
7130 opCode = spv::OpGroupNonUniformBitwiseAnd;
7131 }
7132 break;
7133 case glslang::EOpSubgroupOr:
7134 case glslang::EOpSubgroupInclusiveOr:
7135 case glslang::EOpSubgroupExclusiveOr:
7136 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007137 case glslang::EOpSubgroupPartitionedOr:
7138 case glslang::EOpSubgroupPartitionedInclusiveOr:
7139 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007140 if (isBool) {
7141 opCode = spv::OpGroupNonUniformLogicalOr;
7142 } else {
7143 opCode = spv::OpGroupNonUniformBitwiseOr;
7144 }
7145 break;
7146 case glslang::EOpSubgroupXor:
7147 case glslang::EOpSubgroupInclusiveXor:
7148 case glslang::EOpSubgroupExclusiveXor:
7149 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007150 case glslang::EOpSubgroupPartitionedXor:
7151 case glslang::EOpSubgroupPartitionedInclusiveXor:
7152 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007153 if (isBool) {
7154 opCode = spv::OpGroupNonUniformLogicalXor;
7155 } else {
7156 opCode = spv::OpGroupNonUniformBitwiseXor;
7157 }
7158 break;
7159 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7160 case glslang::EOpSubgroupQuadSwapHorizontal:
7161 case glslang::EOpSubgroupQuadSwapVertical:
7162 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7163 default: assert(0 && "Unhandled subgroup operation!");
7164 }
7165
John Kessenich149afc32018-08-14 13:31:43 -06007166 // get the right Group Operation
7167 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007168 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007169 default:
7170 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007171 case glslang::EOpSubgroupBallotBitCount:
7172 case glslang::EOpSubgroupAdd:
7173 case glslang::EOpSubgroupMul:
7174 case glslang::EOpSubgroupMin:
7175 case glslang::EOpSubgroupMax:
7176 case glslang::EOpSubgroupAnd:
7177 case glslang::EOpSubgroupOr:
7178 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007179 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007180 break;
7181 case glslang::EOpSubgroupBallotInclusiveBitCount:
7182 case glslang::EOpSubgroupInclusiveAdd:
7183 case glslang::EOpSubgroupInclusiveMul:
7184 case glslang::EOpSubgroupInclusiveMin:
7185 case glslang::EOpSubgroupInclusiveMax:
7186 case glslang::EOpSubgroupInclusiveAnd:
7187 case glslang::EOpSubgroupInclusiveOr:
7188 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007189 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007190 break;
7191 case glslang::EOpSubgroupBallotExclusiveBitCount:
7192 case glslang::EOpSubgroupExclusiveAdd:
7193 case glslang::EOpSubgroupExclusiveMul:
7194 case glslang::EOpSubgroupExclusiveMin:
7195 case glslang::EOpSubgroupExclusiveMax:
7196 case glslang::EOpSubgroupExclusiveAnd:
7197 case glslang::EOpSubgroupExclusiveOr:
7198 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007199 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007200 break;
7201 case glslang::EOpSubgroupClusteredAdd:
7202 case glslang::EOpSubgroupClusteredMul:
7203 case glslang::EOpSubgroupClusteredMin:
7204 case glslang::EOpSubgroupClusteredMax:
7205 case glslang::EOpSubgroupClusteredAnd:
7206 case glslang::EOpSubgroupClusteredOr:
7207 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007208 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007209 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007210 case glslang::EOpSubgroupPartitionedAdd:
7211 case glslang::EOpSubgroupPartitionedMul:
7212 case glslang::EOpSubgroupPartitionedMin:
7213 case glslang::EOpSubgroupPartitionedMax:
7214 case glslang::EOpSubgroupPartitionedAnd:
7215 case glslang::EOpSubgroupPartitionedOr:
7216 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007217 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007218 break;
7219 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7220 case glslang::EOpSubgroupPartitionedInclusiveMul:
7221 case glslang::EOpSubgroupPartitionedInclusiveMin:
7222 case glslang::EOpSubgroupPartitionedInclusiveMax:
7223 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7224 case glslang::EOpSubgroupPartitionedInclusiveOr:
7225 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007226 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007227 break;
7228 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7229 case glslang::EOpSubgroupPartitionedExclusiveMul:
7230 case glslang::EOpSubgroupPartitionedExclusiveMin:
7231 case glslang::EOpSubgroupPartitionedExclusiveMax:
7232 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7233 case glslang::EOpSubgroupPartitionedExclusiveOr:
7234 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007235 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007236 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007237 }
7238
John Kessenich149afc32018-08-14 13:31:43 -06007239 // build the instruction
7240 std::vector<spv::IdImmediate> spvGroupOperands;
7241
7242 // Every operation begins with the Execution Scope operand.
7243 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7244 spvGroupOperands.push_back(executionScope);
7245
7246 // Next, for all operations that use a Group Operation, push that as an operand.
7247 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007248 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007249 spvGroupOperands.push_back(groupOperand);
7250 }
7251
John Kessenich66011cb2018-03-06 16:12:04 -07007252 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007253 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7254 spv::IdImmediate operand = { true, *opIt };
7255 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007256 }
7257
7258 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007259 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007260 switch (op) {
7261 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007262 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7263 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7264 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7265 }
7266 if (directionId != spv::NoResult) {
7267 spv::IdImmediate direction = { true, directionId };
7268 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007269 }
7270
7271 return builder.createOp(opCode, typeId, spvGroupOperands);
7272}
7273
John Kessenich8985fc92020-03-03 10:25:07 -07007274spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7275 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007276{
John Kessenich66011cb2018-03-06 16:12:04 -07007277 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7278 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007279
John Kessenich140f3df2015-06-26 16:58:36 -06007280 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007281 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007282 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007283 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007284 spv::Id typeId0 = 0;
7285 if (consumedOperands > 0)
7286 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007287 spv::Id typeId1 = 0;
7288 if (consumedOperands > 1)
7289 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007290 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007291
7292 switch (op) {
7293 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007294 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007295 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007296 else if (isUnsigned)
7297 libCall = spv::GLSLstd450UMin;
7298 else
7299 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007300 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007301 break;
7302 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007303 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007304 break;
7305 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007306 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007307 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007308 else if (isUnsigned)
7309 libCall = spv::GLSLstd450UMax;
7310 else
7311 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007312 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007313 break;
7314 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007315 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007316 break;
7317 case glslang::EOpDot:
7318 opCode = spv::OpDot;
7319 break;
7320 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007321 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007322 break;
7323
7324 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007325 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007326 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007327 else if (isUnsigned)
7328 libCall = spv::GLSLstd450UClamp;
7329 else
7330 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007331 builder.promoteScalar(precision, operands.front(), operands[1]);
7332 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007333 break;
7334 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007335 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7336 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007337 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007338 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007339 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007340 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007341 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007342 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007343 break;
7344 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007345 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007346 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007347 break;
7348 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007349 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007350 builder.promoteScalar(precision, operands[0], operands[2]);
7351 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007352 break;
7353
7354 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007355 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007356 break;
7357 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007358 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007359 break;
7360 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007361 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007362 break;
7363 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007364 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007365 break;
7366 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007367 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007368 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007369 case glslang::EOpBarrier:
7370 {
7371 // This is for the extended controlBarrier function, with four operands.
7372 // The unextended barrier() goes through createNoArgOperation.
7373 assert(operands.size() == 4);
7374 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7375 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7376 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007377 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7378 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007379 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7380 spv::MemorySemanticsMakeVisibleKHRMask |
7381 spv::MemorySemanticsOutputMemoryKHRMask |
7382 spv::MemorySemanticsVolatileMask)) {
7383 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7384 }
John Kessenich8985fc92020-03-03 10:25:07 -07007385 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7386 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007387 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7388 }
7389 return 0;
7390 }
7391 break;
7392 case glslang::EOpMemoryBarrier:
7393 {
7394 // This is for the extended memoryBarrier function, with three operands.
7395 // The unextended memoryBarrier() goes through createNoArgOperation.
7396 assert(operands.size() == 3);
7397 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7398 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7399 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7400 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7401 spv::MemorySemanticsMakeVisibleKHRMask |
7402 spv::MemorySemanticsOutputMemoryKHRMask |
7403 spv::MemorySemanticsVolatileMask)) {
7404 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7405 }
7406 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7407 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7408 }
7409 return 0;
7410 }
7411 break;
7412
John Kessenicha28f7a72019-08-06 07:00:58 -06007413#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007414 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007415 if (typeProxy == glslang::EbtFloat16)
7416 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007417 libCall = spv::GLSLstd450InterpolateAtSample;
7418 break;
7419 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007420 if (typeProxy == glslang::EbtFloat16)
7421 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007422 libCall = spv::GLSLstd450InterpolateAtOffset;
7423 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007424 case glslang::EOpAddCarry:
7425 opCode = spv::OpIAddCarry;
7426 typeId = builder.makeStructResultType(typeId0, typeId0);
7427 consumedOperands = 2;
7428 break;
7429 case glslang::EOpSubBorrow:
7430 opCode = spv::OpISubBorrow;
7431 typeId = builder.makeStructResultType(typeId0, typeId0);
7432 consumedOperands = 2;
7433 break;
7434 case glslang::EOpUMulExtended:
7435 opCode = spv::OpUMulExtended;
7436 typeId = builder.makeStructResultType(typeId0, typeId0);
7437 consumedOperands = 2;
7438 break;
7439 case glslang::EOpIMulExtended:
7440 opCode = spv::OpSMulExtended;
7441 typeId = builder.makeStructResultType(typeId0, typeId0);
7442 consumedOperands = 2;
7443 break;
7444 case glslang::EOpBitfieldExtract:
7445 if (isUnsigned)
7446 opCode = spv::OpBitFieldUExtract;
7447 else
7448 opCode = spv::OpBitFieldSExtract;
7449 break;
7450 case glslang::EOpBitfieldInsert:
7451 opCode = spv::OpBitFieldInsert;
7452 break;
7453
7454 case glslang::EOpFma:
7455 libCall = spv::GLSLstd450Fma;
7456 break;
7457 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007458 {
7459 libCall = spv::GLSLstd450FrexpStruct;
7460 assert(builder.isPointerType(typeId1));
7461 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007462 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007463 if (width == 16)
7464 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7465 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007466 if (builder.getNumComponents(operands[0]) == 1)
7467 frexpIntType = builder.makeIntegerType(width, true);
7468 else
John Kessenich8985fc92020-03-03 10:25:07 -07007469 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7470 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007471 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7472 consumedOperands = 1;
7473 }
John Kessenich55e7d112015-11-15 21:33:39 -07007474 break;
7475 case glslang::EOpLdexp:
7476 libCall = spv::GLSLstd450Ldexp;
7477 break;
7478
Rex Xu574ab042016-04-14 16:53:07 +08007479 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007480 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007481
John Kessenich66011cb2018-03-06 16:12:04 -07007482 case glslang::EOpSubgroupBroadcast:
7483 case glslang::EOpSubgroupBallotBitExtract:
7484 case glslang::EOpSubgroupShuffle:
7485 case glslang::EOpSubgroupShuffleXor:
7486 case glslang::EOpSubgroupShuffleUp:
7487 case glslang::EOpSubgroupShuffleDown:
7488 case glslang::EOpSubgroupClusteredAdd:
7489 case glslang::EOpSubgroupClusteredMul:
7490 case glslang::EOpSubgroupClusteredMin:
7491 case glslang::EOpSubgroupClusteredMax:
7492 case glslang::EOpSubgroupClusteredAnd:
7493 case glslang::EOpSubgroupClusteredOr:
7494 case glslang::EOpSubgroupClusteredXor:
7495 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007496 case glslang::EOpSubgroupPartitionedAdd:
7497 case glslang::EOpSubgroupPartitionedMul:
7498 case glslang::EOpSubgroupPartitionedMin:
7499 case glslang::EOpSubgroupPartitionedMax:
7500 case glslang::EOpSubgroupPartitionedAnd:
7501 case glslang::EOpSubgroupPartitionedOr:
7502 case glslang::EOpSubgroupPartitionedXor:
7503 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7504 case glslang::EOpSubgroupPartitionedInclusiveMul:
7505 case glslang::EOpSubgroupPartitionedInclusiveMin:
7506 case glslang::EOpSubgroupPartitionedInclusiveMax:
7507 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7508 case glslang::EOpSubgroupPartitionedInclusiveOr:
7509 case glslang::EOpSubgroupPartitionedInclusiveXor:
7510 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7511 case glslang::EOpSubgroupPartitionedExclusiveMul:
7512 case glslang::EOpSubgroupPartitionedExclusiveMin:
7513 case glslang::EOpSubgroupPartitionedExclusiveMax:
7514 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7515 case glslang::EOpSubgroupPartitionedExclusiveOr:
7516 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007517 return createSubgroupOperation(op, typeId, operands, typeProxy);
7518
Rex Xu9d93a232016-05-05 12:30:44 +08007519 case glslang::EOpSwizzleInvocations:
7520 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7521 libCall = spv::SwizzleInvocationsAMD;
7522 break;
7523 case glslang::EOpSwizzleInvocationsMasked:
7524 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7525 libCall = spv::SwizzleInvocationsMaskedAMD;
7526 break;
7527 case glslang::EOpWriteInvocation:
7528 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7529 libCall = spv::WriteInvocationAMD;
7530 break;
7531
7532 case glslang::EOpMin3:
7533 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7534 if (isFloat)
7535 libCall = spv::FMin3AMD;
7536 else {
7537 if (isUnsigned)
7538 libCall = spv::UMin3AMD;
7539 else
7540 libCall = spv::SMin3AMD;
7541 }
7542 break;
7543 case glslang::EOpMax3:
7544 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7545 if (isFloat)
7546 libCall = spv::FMax3AMD;
7547 else {
7548 if (isUnsigned)
7549 libCall = spv::UMax3AMD;
7550 else
7551 libCall = spv::SMax3AMD;
7552 }
7553 break;
7554 case glslang::EOpMid3:
7555 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7556 if (isFloat)
7557 libCall = spv::FMid3AMD;
7558 else {
7559 if (isUnsigned)
7560 libCall = spv::UMid3AMD;
7561 else
7562 libCall = spv::SMid3AMD;
7563 }
7564 break;
7565
7566 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007567 if (typeProxy == glslang::EbtFloat16)
7568 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007569 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7570 libCall = spv::InterpolateAtVertexAMD;
7571 break;
Chao Chen3c366992018-09-19 11:41:59 -07007572
Chao Chenb50c02e2018-09-19 11:42:24 -07007573 case glslang::EOpReportIntersectionNV:
7574 {
7575 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007576 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007577 }
7578 break;
7579 case glslang::EOpTraceNV:
7580 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007581 builder.createNoResultOp(spv::OpTraceNV, operands);
7582 return 0;
7583 }
7584 break;
7585 case glslang::EOpExecuteCallableNV:
7586 {
7587 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007588 return 0;
7589 }
7590 break;
Chao Chen3c366992018-09-19 11:41:59 -07007591 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7592 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7593 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007594 case glslang::EOpCooperativeMatrixMulAdd:
7595 opCode = spv::OpCooperativeMatrixMulAddNV;
7596 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007597#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007598 default:
7599 return 0;
7600 }
7601
7602 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007603 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007604 // Use an extended instruction from the standard library.
7605 // Construct the call arguments, without modifying the original operands vector.
7606 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7607 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007608 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007609 } else if (opCode == spv::OpDot && !isFloat) {
7610 // int dot(int, int)
7611 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7612 const int componentCount = builder.getNumComponents(operands[0]);
7613 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7614 builder.setPrecision(mulOp, precision);
7615 id = builder.createCompositeExtract(mulOp, typeId, 0);
7616 for (int i = 1; i < componentCount; ++i) {
7617 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007618 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007619 }
John Kessenich2359bd02015-12-06 19:29:11 -07007620 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007621 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007622 case 0:
7623 // should all be handled by visitAggregate and createNoArgOperation
7624 assert(0);
7625 return 0;
7626 case 1:
7627 // should all be handled by createUnaryOperation
7628 assert(0);
7629 return 0;
7630 case 2:
7631 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7632 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007633 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007634 // anything 3 or over doesn't have l-value operands, so all should be consumed
7635 assert(consumedOperands == operands.size());
7636 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007637 break;
7638 }
7639 }
7640
John Kessenichb9197c82019-08-11 07:41:45 -06007641#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007642 // Decode the return types that were structures
7643 switch (op) {
7644 case glslang::EOpAddCarry:
7645 case glslang::EOpSubBorrow:
7646 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7647 id = builder.createCompositeExtract(id, typeId0, 0);
7648 break;
7649 case glslang::EOpUMulExtended:
7650 case glslang::EOpIMulExtended:
7651 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7652 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7653 break;
7654 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007655 {
7656 assert(operands.size() == 2);
7657 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7658 // "exp" is floating-point type (from HLSL intrinsic)
7659 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7660 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7661 builder.createStore(member1, operands[1]);
7662 } else
7663 // "exp" is integer type (from GLSL built-in function)
7664 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7665 id = builder.createCompositeExtract(id, typeId0, 0);
7666 }
John Kessenich55e7d112015-11-15 21:33:39 -07007667 break;
7668 default:
7669 break;
7670 }
John Kessenichb9197c82019-08-11 07:41:45 -06007671#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007672
John Kessenich32cfd492016-02-02 12:37:46 -07007673 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007674}
7675
Rex Xu9d93a232016-05-05 12:30:44 +08007676// Intrinsics with no arguments (or no return value, and no precision).
7677spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007678{
Jeff Bolz36831c92018-09-05 10:11:41 -05007679 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007680 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7681 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007682
7683 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007684 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007685 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007686 if (glslangIntermediate->usingVulkanMemoryModel()) {
7687 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7688 spv::MemorySemanticsOutputMemoryKHRMask |
7689 spv::MemorySemanticsAcquireReleaseMask);
7690 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7691 } else {
7692 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7693 }
John Kessenich82979362017-12-11 04:02:24 -07007694 } else {
7695 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7696 spv::MemorySemanticsWorkgroupMemoryMask |
7697 spv::MemorySemanticsAcquireReleaseMask);
7698 }
John Kessenich140f3df2015-06-26 16:58:36 -06007699 return 0;
7700 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007701 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7702 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007703 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007704 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007705 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7706 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007707 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007708 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007709 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7710 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007711 return 0;
7712 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007713 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7714 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007715 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007716#ifndef GLSLANG_WEB
7717 case glslang::EOpMemoryBarrierAtomicCounter:
7718 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7719 spv::MemorySemanticsAcquireReleaseMask);
7720 return 0;
7721 case glslang::EOpMemoryBarrierImage:
7722 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7723 spv::MemorySemanticsAcquireReleaseMask);
7724 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007725 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007726 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007727 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007728 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007729 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007730 case glslang::EOpDeviceMemoryBarrier:
7731 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7732 spv::MemorySemanticsImageMemoryMask |
7733 spv::MemorySemanticsAcquireReleaseMask);
7734 return 0;
7735 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7736 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7737 spv::MemorySemanticsImageMemoryMask |
7738 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007739 return 0;
7740 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007741 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7742 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007743 return 0;
7744 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007745 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7746 spv::MemorySemanticsWorkgroupMemoryMask |
7747 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007748 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007749 case glslang::EOpSubgroupBarrier:
7750 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7751 spv::MemorySemanticsAcquireReleaseMask);
7752 return spv::NoResult;
7753 case glslang::EOpSubgroupMemoryBarrier:
7754 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7755 spv::MemorySemanticsAcquireReleaseMask);
7756 return spv::NoResult;
7757 case glslang::EOpSubgroupMemoryBarrierBuffer:
7758 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7759 spv::MemorySemanticsAcquireReleaseMask);
7760 return spv::NoResult;
7761 case glslang::EOpSubgroupMemoryBarrierImage:
7762 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7763 spv::MemorySemanticsAcquireReleaseMask);
7764 return spv::NoResult;
7765 case glslang::EOpSubgroupMemoryBarrierShared:
7766 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7767 spv::MemorySemanticsAcquireReleaseMask);
7768 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007769
7770 case glslang::EOpEmitVertex:
7771 builder.createNoResultOp(spv::OpEmitVertex);
7772 return 0;
7773 case glslang::EOpEndPrimitive:
7774 builder.createNoResultOp(spv::OpEndPrimitive);
7775 return 0;
7776
John Kessenich66011cb2018-03-06 16:12:04 -07007777 case glslang::EOpSubgroupElect: {
7778 std::vector<spv::Id> operands;
7779 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7780 }
Rex Xu9d93a232016-05-05 12:30:44 +08007781 case glslang::EOpTime:
7782 {
7783 std::vector<spv::Id> args; // Dummy arguments
7784 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7785 return builder.setPrecision(id, precision);
7786 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007787 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007788 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007789 return 0;
7790 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007791 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007792 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007793
7794 case glslang::EOpBeginInvocationInterlock:
7795 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7796 return 0;
7797 case glslang::EOpEndInvocationInterlock:
7798 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7799 return 0;
7800
Jeff Bolzba6170b2019-07-01 09:23:23 -05007801 case glslang::EOpIsHelperInvocation:
7802 {
7803 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007804 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7805 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7806 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007807 }
7808
amhagan91fb0092019-07-10 21:14:38 -04007809 case glslang::EOpReadClockSubgroupKHR: {
7810 std::vector<spv::Id> args;
7811 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7812 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7813 builder.addCapability(spv::CapabilityShaderClockKHR);
7814 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7815 }
7816
7817 case glslang::EOpReadClockDeviceKHR: {
7818 std::vector<spv::Id> args;
7819 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7820 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7821 builder.addCapability(spv::CapabilityShaderClockKHR);
7822 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7823 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007824#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007825 default:
John Kessenich155d3512019-08-08 23:29:20 -06007826 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007827 }
John Kessenich155d3512019-08-08 23:29:20 -06007828
7829 logger->missingFunctionality("unknown operation with no arguments");
7830
7831 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007832}
7833
7834spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7835{
John Kessenich2f273362015-07-18 22:34:27 -06007836 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007837 spv::Id id;
7838 if (symbolValues.end() != iter) {
7839 id = iter->second;
7840 return id;
7841 }
7842
7843 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007844 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7845 auto forcedType = getForcedType(builtIn, symbol->getType());
7846 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007847 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007848 if (forcedType.second != spv::NoType)
7849 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007850
Rex Xuc884b4a2016-06-29 15:03:44 +08007851 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007852 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7853 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7854 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007855#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007856 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007857 if (symbol->getQualifier().hasComponent())
7858 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7859 if (symbol->getQualifier().hasIndex())
7860 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007861#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007862 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007863 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007864 // atomic counters use this:
7865 if (symbol->getQualifier().hasOffset())
7866 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007867 }
7868
scygan2c864272016-05-18 18:09:17 +02007869 if (symbol->getQualifier().hasLocation())
7870 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007871 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007872 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007873 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007874 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007875 }
John Kessenich140f3df2015-06-26 16:58:36 -06007876 if (symbol->getQualifier().hasSet())
7877 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007878 else if (IsDescriptorResource(symbol->getType())) {
7879 // default to 0
7880 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7881 }
John Kessenich140f3df2015-06-26 16:58:36 -06007882 if (symbol->getQualifier().hasBinding())
7883 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007884 else if (IsDescriptorResource(symbol->getType())) {
7885 // default to 0
7886 builder.addDecoration(id, spv::DecorationBinding, 0);
7887 }
John Kessenich6c292d32016-02-15 20:58:50 -07007888 if (symbol->getQualifier().hasAttachment())
7889 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007890 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007891 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007892 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007893 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007894 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7895 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7896 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7897 }
7898 if (symbol->getQualifier().hasXfbOffset())
7899 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007900 }
7901
John Kessenichb9197c82019-08-11 07:41:45 -06007902 // add built-in variable decoration
7903 if (builtIn != spv::BuiltInMax) {
7904 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7905 }
7906
7907#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007908 if (symbol->getType().isImage()) {
7909 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07007910 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
7911 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007912 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007913 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007914 }
7915
John Kessenich5611c6d2018-04-05 11:25:02 -06007916 // nonuniform
7917 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7918
chaoc0ad6a4e2016-12-19 16:29:34 -08007919 if (builtIn == spv::BuiltInSampleMask) {
7920 spv::Decoration decoration;
7921 // GL_NV_sample_mask_override_coverage extension
7922 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007923 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007924 else
7925 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007926 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007927 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007928 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007929 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7930 }
7931 }
chaoc771d89f2017-01-13 01:10:53 -08007932 else if (builtIn == spv::BuiltInLayer) {
7933 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007934 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007935 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007936 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7937 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7938 }
John Kessenichb41bff62017-08-11 13:07:17 -06007939 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007940 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7941 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007942 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7943 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7944 }
7945 }
7946
chaoc6e5acae2016-12-20 13:28:52 -08007947 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007948 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007949 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007950 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7951 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007952 if (symbol->getQualifier().pervertexNV) {
7953 builder.addDecoration(id, spv::DecorationPerVertexNV);
7954 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7955 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7956 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007957
John Kessenich5d610ee2018-03-07 18:05:55 -07007958 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7959 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7960 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7961 symbol->getType().getQualifier().semanticName);
7962 }
7963
John Kessenich7015bd62019-08-01 03:28:08 -06007964 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07007965 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
7966 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007967 }
John Kessenichb9197c82019-08-11 07:41:45 -06007968#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007969
John Kessenich140f3df2015-06-26 16:58:36 -06007970 return id;
7971}
7972
John Kessenicha28f7a72019-08-06 07:00:58 -06007973#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007974// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7975void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7976{
7977 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007978 if (qualifier.perPrimitiveNV) {
7979 // Need to add capability/extension for fragment shader.
7980 // Mesh shader already adds this by default.
7981 if (glslangIntermediate->getStage() == EShLangFragment) {
7982 builder.addCapability(spv::CapabilityMeshShadingNV);
7983 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7984 }
Chao Chen3c366992018-09-19 11:41:59 -07007985 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007986 }
Chao Chen3c366992018-09-19 11:41:59 -07007987 if (qualifier.perViewNV)
7988 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7989 if (qualifier.perTaskNV)
7990 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7991 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007992 if (qualifier.perPrimitiveNV) {
7993 // Need to add capability/extension for fragment shader.
7994 // Mesh shader already adds this by default.
7995 if (glslangIntermediate->getStage() == EShLangFragment) {
7996 builder.addCapability(spv::CapabilityMeshShadingNV);
7997 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7998 }
Chao Chen3c366992018-09-19 11:41:59 -07007999 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008000 }
Chao Chen3c366992018-09-19 11:41:59 -07008001 if (qualifier.perViewNV)
8002 builder.addDecoration(id, spv::DecorationPerViewNV);
8003 if (qualifier.perTaskNV)
8004 builder.addDecoration(id, spv::DecorationPerTaskNV);
8005 }
8006}
8007#endif
8008
John Kessenich55e7d112015-11-15 21:33:39 -07008009// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008010// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008011//
8012// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8013//
8014// Recursively walk the nodes. The nodes form a tree whose leaves are
8015// regular constants, which themselves are trees that createSpvConstant()
8016// recursively walks. So, this function walks the "top" of the tree:
8017// - emit specialization constant-building instructions for specConstant
8018// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008019spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008020{
John Kessenich7cc0e282016-03-20 00:46:02 -06008021 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008022
qining4f4bb812016-04-03 23:55:17 -04008023 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008024 if (! node.getQualifier().specConstant) {
8025 // hand off to the non-spec-constant path
8026 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8027 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008028 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8029 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8030 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008031 }
8032
8033 // We now know we have a specialization constant to build
8034
John Kessenichd94c0032016-05-30 19:29:40 -06008035 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008036 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8037 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8038 std::vector<spv::Id> dimConstId;
8039 for (int dim = 0; dim < 3; ++dim) {
8040 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8041 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008042 if (specConst) {
8043 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8044 glslangIntermediate->getLocalSizeSpecId(dim));
8045 }
qining4f4bb812016-04-03 23:55:17 -04008046 }
8047 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8048 }
8049
8050 // An AST node labelled as specialization constant should be a symbol node.
8051 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8052 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008053 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008054 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008055 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8056 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8057 // will set the builder into spec constant op instruction generating mode.
8058 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008059 result = accessChainLoad(sub_tree->getType());
8060 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008061 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008062 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008063 } else {
8064 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008065 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008066 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008067 builder.addName(result, sn->getName().c_str());
8068 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008069 }
qining4f4bb812016-04-03 23:55:17 -04008070
8071 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8072 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008073 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008074 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008075}
8076
John Kessenich140f3df2015-06-26 16:58:36 -06008077// Use 'consts' as the flattened glslang source of scalar constants to recursively
8078// build the aggregate SPIR-V constant.
8079//
8080// If there are not enough elements present in 'consts', 0 will be substituted;
8081// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8082//
John Kessenich8985fc92020-03-03 10:25:07 -07008083spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8084 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008085{
8086 // vector of constants for SPIR-V
8087 std::vector<spv::Id> spvConsts;
8088
8089 // Type is used for struct and array constants
8090 spv::Id typeId = convertGlslangToSpvType(glslangType);
8091
8092 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008093 glslang::TType elementType(glslangType, 0);
8094 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008095 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008096 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008097 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008098 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008099 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008100 } else if (glslangType.isCoopMat()) {
8101 glslang::TType componentType(glslangType.getBasicType());
8102 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008103 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008104 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8105 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008106 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008107 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008108 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8109 bool zero = nextConst >= consts.size();
8110 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008111 case glslang::EbtInt:
8112 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8113 break;
8114 case glslang::EbtUint:
8115 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8116 break;
8117 case glslang::EbtFloat:
8118 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8119 break;
8120 case glslang::EbtBool:
8121 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8122 break;
8123#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008124 case glslang::EbtInt8:
8125 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8126 break;
8127 case glslang::EbtUint8:
8128 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8129 break;
8130 case glslang::EbtInt16:
8131 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8132 break;
8133 case glslang::EbtUint16:
8134 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8135 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008136 case glslang::EbtInt64:
8137 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8138 break;
8139 case glslang::EbtUint64:
8140 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8141 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008142 case glslang::EbtDouble:
8143 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8144 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008145 case glslang::EbtFloat16:
8146 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8147 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008148#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008149 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008150 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008151 break;
8152 }
8153 ++nextConst;
8154 }
8155 } else {
8156 // we have a non-aggregate (scalar) constant
8157 bool zero = nextConst >= consts.size();
8158 spv::Id scalar = 0;
8159 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008160 case glslang::EbtInt:
8161 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8162 break;
8163 case glslang::EbtUint:
8164 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8165 break;
8166 case glslang::EbtFloat:
8167 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8168 break;
8169 case glslang::EbtBool:
8170 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8171 break;
8172#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008173 case glslang::EbtInt8:
8174 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8175 break;
8176 case glslang::EbtUint8:
8177 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8178 break;
8179 case glslang::EbtInt16:
8180 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8181 break;
8182 case glslang::EbtUint16:
8183 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8184 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008185 case glslang::EbtInt64:
8186 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8187 break;
8188 case glslang::EbtUint64:
8189 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8190 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008191 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008192 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008193 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008194 case glslang::EbtFloat16:
8195 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8196 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008197 case glslang::EbtReference:
8198 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8199 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8200 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008201#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008202 case glslang::EbtString:
8203 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8204 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008205 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008206 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008207 break;
8208 }
8209 ++nextConst;
8210 return scalar;
8211 }
8212
8213 return builder.makeCompositeConstant(typeId, spvConsts);
8214}
8215
John Kessenich7c1aa102015-10-15 13:29:11 -06008216// Return true if the node is a constant or symbol whose reading has no
8217// non-trivial observable cost or effect.
8218bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8219{
8220 // don't know what this is
8221 if (node == nullptr)
8222 return false;
8223
8224 // a constant is safe
8225 if (node->getAsConstantUnion() != nullptr)
8226 return true;
8227
8228 // not a symbol means non-trivial
8229 if (node->getAsSymbolNode() == nullptr)
8230 return false;
8231
8232 // a symbol, depends on what's being read
8233 switch (node->getType().getQualifier().storage) {
8234 case glslang::EvqTemporary:
8235 case glslang::EvqGlobal:
8236 case glslang::EvqIn:
8237 case glslang::EvqInOut:
8238 case glslang::EvqConst:
8239 case glslang::EvqConstReadOnly:
8240 case glslang::EvqUniform:
8241 return true;
8242 default:
8243 return false;
8244 }
qining25262b32016-05-06 17:25:16 -04008245}
John Kessenich7c1aa102015-10-15 13:29:11 -06008246
8247// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008248// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008249// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008250// Return true if trivial.
8251bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8252{
8253 if (node == nullptr)
8254 return false;
8255
John Kessenich84cc15f2017-05-24 16:44:47 -06008256 // count non scalars as trivial, as well as anything coming from HLSL
8257 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008258 return true;
8259
John Kessenich7c1aa102015-10-15 13:29:11 -06008260 // symbols and constants are trivial
8261 if (isTrivialLeaf(node))
8262 return true;
8263
8264 // otherwise, it needs to be a simple operation or one or two leaf nodes
8265
8266 // not a simple operation
8267 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8268 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8269 if (binaryNode == nullptr && unaryNode == nullptr)
8270 return false;
8271
8272 // not on leaf nodes
8273 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8274 return false;
8275
8276 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8277 return false;
8278 }
8279
8280 switch (node->getAsOperator()->getOp()) {
8281 case glslang::EOpLogicalNot:
8282 case glslang::EOpConvIntToBool:
8283 case glslang::EOpConvUintToBool:
8284 case glslang::EOpConvFloatToBool:
8285 case glslang::EOpConvDoubleToBool:
8286 case glslang::EOpEqual:
8287 case glslang::EOpNotEqual:
8288 case glslang::EOpLessThan:
8289 case glslang::EOpGreaterThan:
8290 case glslang::EOpLessThanEqual:
8291 case glslang::EOpGreaterThanEqual:
8292 case glslang::EOpIndexDirect:
8293 case glslang::EOpIndexDirectStruct:
8294 case glslang::EOpLogicalXor:
8295 case glslang::EOpAny:
8296 case glslang::EOpAll:
8297 return true;
8298 default:
8299 return false;
8300 }
8301}
8302
8303// Emit short-circuiting code, where 'right' is never evaluated unless
8304// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008305spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8306 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008307{
8308 spv::Id boolTypeId = builder.makeBoolType();
8309
8310 // emit left operand
8311 builder.clearAccessChain();
8312 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008313 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008314
8315 // Operands to accumulate OpPhi operands
8316 std::vector<spv::Id> phiOperands;
8317 // accumulate left operand's phi information
8318 phiOperands.push_back(leftId);
8319 phiOperands.push_back(builder.getBuildPoint()->getId());
8320
8321 // Make the two kinds of operation symmetric with a "!"
8322 // || => emit "if (! left) result = right"
8323 // && => emit "if ( left) result = right"
8324 //
8325 // TODO: this runtime "not" for || could be avoided by adding functionality
8326 // to 'builder' to have an "else" without an "then"
8327 if (op == glslang::EOpLogicalOr)
8328 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8329
8330 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008331 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008332
8333 // emit right operand as the "then" part of the "if"
8334 builder.clearAccessChain();
8335 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008336 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008337
8338 // accumulate left operand's phi information
8339 phiOperands.push_back(rightId);
8340 phiOperands.push_back(builder.getBuildPoint()->getId());
8341
8342 // finish the "if"
8343 ifBuilder.makeEndIf();
8344
8345 // phi together the two results
8346 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8347}
8348
John Kessenicha28f7a72019-08-06 07:00:58 -06008349#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008350// Return type Id of the imported set of extended instructions corresponds to the name.
8351// Import this set if it has not been imported yet.
8352spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8353{
8354 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8355 return extBuiltinMap[name];
8356 else {
Rex Xu51596642016-09-21 18:56:12 +08008357 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008358 spv::Id extBuiltins = builder.import(name);
8359 extBuiltinMap[name] = extBuiltins;
8360 return extBuiltins;
8361 }
8362}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008363#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008364
John Kessenich140f3df2015-06-26 16:58:36 -06008365}; // end anonymous namespace
8366
8367namespace glslang {
8368
John Kessenich68d78fd2015-07-12 19:28:10 -06008369void GetSpirvVersion(std::string& version)
8370{
John Kessenich9e55f632015-07-15 10:03:39 -06008371 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008372 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008373 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008374 version = buf;
8375}
8376
John Kessenicha372a3e2017-11-02 22:32:14 -06008377// For low-order part of the generator's magic number. Bump up
8378// when there is a change in the style (e.g., if SSA form changes,
8379// or a different instruction sequence to do something gets used).
8380int GetSpirvGeneratorVersion()
8381{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008382 // return 1; // start
8383 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008384 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008385 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008386 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008387 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8388 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008389 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8390 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008391}
8392
John Kessenich140f3df2015-06-26 16:58:36 -06008393// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008394void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008395{
8396 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008397 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008398 if (out.fail())
8399 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008400 for (int i = 0; i < (int)spirv.size(); ++i) {
8401 unsigned int word = spirv[i];
8402 out.write((const char*)&word, 4);
8403 }
8404 out.close();
8405}
8406
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008407// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008408void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008409{
John Kessenich155d3512019-08-08 23:29:20 -06008410#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008411 std::ofstream out;
8412 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008413 if (out.fail())
8414 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008415 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008416 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008417 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008418 if (varName != nullptr) {
8419 out << "\t #pragma once" << std::endl;
8420 out << "const uint32_t " << varName << "[] = {" << std::endl;
8421 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008422 const int WORDS_PER_LINE = 8;
8423 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8424 out << "\t";
8425 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8426 const unsigned int word = spirv[i + j];
8427 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8428 if (i + j + 1 < (int)spirv.size()) {
8429 out << ",";
8430 }
8431 }
8432 out << std::endl;
8433 }
Flavio15017db2017-02-15 14:29:33 -08008434 if (varName != nullptr) {
8435 out << "};";
8436 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008437 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008438#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008439}
8440
John Kessenich140f3df2015-06-26 16:58:36 -06008441//
8442// Set up the glslang traversal
8443//
John Kessenich4e11b612018-08-30 16:56:59 -06008444void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008445{
Lei Zhang17535f72016-05-04 15:55:59 -04008446 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008447 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008448}
8449
John Kessenich4e11b612018-08-30 16:56:59 -06008450void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008451 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008452{
John Kessenich140f3df2015-06-26 16:58:36 -06008453 TIntermNode* root = intermediate.getTreeRoot();
8454
8455 if (root == 0)
8456 return;
8457
John Kessenich4e11b612018-08-30 16:56:59 -06008458 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008459 if (options == nullptr)
8460 options = &defaultOptions;
8461
John Kessenich4e11b612018-08-30 16:56:59 -06008462 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008463
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008464 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008465 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008466 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008467 it.dumpSpv(spirv);
8468
GregFfb03a552018-03-29 11:49:14 -06008469#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008470 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8471 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008472 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8473 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008474 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008475 prelegalization = false;
8476 }
John Kessenich717c80a2018-08-23 15:17:10 -06008477
John Kessenich4e11b612018-08-30 16:56:59 -06008478 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008479 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008480
John Kessenich717c80a2018-08-23 15:17:10 -06008481 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008482 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008483
GregFcd1f1692017-09-21 18:40:22 -06008484#endif
8485
John Kessenich4e11b612018-08-30 16:56:59 -06008486 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008487}
8488
8489}; // end namespace glslang