blob: 5787e3d5261d2696a584f0ddb993a51c7c4c054d [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);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004838 if (imageType.getQualifier().nonUniform) {
4839 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4840 }
Rex Xufc618912015-09-09 16:42:49 +08004841
4842 std::vector<spv::Id> operands;
4843 operands.push_back(pointer);
4844 for (; opIt != arguments.end(); ++opIt)
4845 operands.push_back(*opIt);
4846
John Kessenich8985fc92020-03-03 10:25:07 -07004847 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4848 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004849 }
4850 }
4851
John Kessenicha28f7a72019-08-06 07:00:58 -06004852#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004853 // Check for fragment mask functions other than queries
4854 if (cracked.fragMask) {
4855 assert(sampler.ms);
4856
4857 auto opIt = arguments.begin();
4858 std::vector<spv::Id> operands;
4859
4860 // Extract the image if necessary
4861 if (builder.isSampledImage(params.sampler))
4862 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4863
4864 operands.push_back(params.sampler);
4865 ++opIt;
4866
4867 if (sampler.isSubpass()) {
4868 // add on the (0,0) coordinate
4869 spv::Id zero = builder.makeIntConstant(0);
4870 std::vector<spv::Id> comps;
4871 comps.push_back(zero);
4872 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004873 operands.push_back(builder.makeCompositeConstant(
4874 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04004875 }
4876
4877 for (; opIt != arguments.end(); ++opIt)
4878 operands.push_back(*opIt);
4879
4880 spv::Op fragMaskOp = spv::OpNop;
4881 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4882 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4883 else if (node->getOp() == glslang::EOpFragmentFetch)
4884 fragMaskOp = spv::OpFragmentFetchAMD;
4885
4886 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4887 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4888 return builder.createOp(fragMaskOp, resultType(), operands);
4889 }
4890#endif
4891
Rex Xufc618912015-09-09 16:42:49 +08004892 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004893 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004894 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004895 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004896
John Kessenichfc51d282015-08-19 13:34:18 -06004897 // check for bias argument
4898 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004899 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004900 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004901 if (cracked.gather)
4902 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004903
4904 if (f16ShadowCompare)
4905 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004906 if (cracked.offset)
4907 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004908 else if (cracked.offsets)
4909 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004910 if (cracked.grad)
4911 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004912 if (cracked.lodClamp)
4913 ++nonBiasArgCount;
4914 if (sparse)
4915 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004916 if (imageFootprint)
4917 //Following three extra arguments
4918 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4919 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004920 if ((int)arguments.size() > nonBiasArgCount)
4921 bias = true;
4922 }
4923
John Kessenicha5c33d62016-06-02 23:45:21 -06004924 // See if the sampler param should really be just the SPV image part
4925 if (cracked.fetch) {
4926 // a fetch needs to have the image extracted first
4927 if (builder.isSampledImage(params.sampler))
4928 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4929 }
4930
John Kessenicha28f7a72019-08-06 07:00:58 -06004931#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004932 if (cracked.gather) {
4933 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4934 if (bias || cracked.lod ||
4935 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4936 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004937 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004938 }
4939 }
4940#endif
4941
John Kessenichfc51d282015-08-19 13:34:18 -06004942 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004943
John Kessenichfc51d282015-08-19 13:34:18 -06004944 params.coords = arguments[1];
4945 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004946 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004947
4948 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004949 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004950 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004951 ++extraArgs;
4952 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004953 params.Dref = arguments[2];
4954 ++extraArgs;
4955 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004956 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004957 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004958 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004959 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004960 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004961 dRefComp = builder.getNumComponents(params.coords) - 1;
4962 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07004963 params.Dref = builder.createCompositeExtract(params.coords,
4964 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06004965 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004966
4967 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004968 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004969 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004970 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004971 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4972 !(glslangIntermediate->getStage() == EShLangCompute &&
4973 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004974 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4975 noImplicitLod = true;
4976 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004977
4978 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004979 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004980 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004981 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004982 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004983
4984 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004985 if (cracked.grad) {
4986 params.gradX = arguments[2 + extraArgs];
4987 params.gradY = arguments[3 + extraArgs];
4988 extraArgs += 2;
4989 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004990
4991 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004992 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004993 params.offset = arguments[2 + extraArgs];
4994 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004995 } else if (cracked.offsets) {
4996 params.offsets = arguments[2 + extraArgs];
4997 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004998 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004999
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005000#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005001 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005002 if (cracked.lodClamp) {
5003 params.lodClamp = arguments[2 + extraArgs];
5004 ++extraArgs;
5005 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005006 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005007 if (sparse) {
5008 params.texelOut = arguments[2 + extraArgs];
5009 ++extraArgs;
5010 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005011 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005012 if (cracked.gather && ! sampler.shadow) {
5013 // default component is 0, if missing, otherwise an argument
5014 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005015 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005016 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005017 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005018 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005019 }
Chao Chen3a137962018-09-19 11:41:27 -07005020 spv::Id resultStruct = spv::NoResult;
5021 if (imageFootprint) {
5022 //Following three extra arguments
5023 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5024 params.granularity = arguments[2 + extraArgs];
5025 params.coarse = arguments[3 + extraArgs];
5026 resultStruct = arguments[4 + extraArgs];
5027 extraArgs += 3;
5028 }
5029#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005030 // bias
5031 if (bias) {
5032 params.bias = arguments[2 + extraArgs];
5033 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005034 }
John Kessenichfc51d282015-08-19 13:34:18 -06005035
John Kessenicha28f7a72019-08-06 07:00:58 -06005036#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005037 if (imageFootprint) {
5038 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5039 builder.addCapability(spv::CapabilityImageFootprintNV);
5040
5041
5042 //resultStructType(OpenGL type) contains 5 elements:
5043 //struct gl_TextureFootprint2DNV {
5044 // uvec2 anchor;
5045 // uvec2 offset;
5046 // uvec2 mask;
5047 // uint lod;
5048 // uint granularity;
5049 //};
5050 //or
5051 //struct gl_TextureFootprint3DNV {
5052 // uvec3 anchor;
5053 // uvec3 offset;
5054 // uvec2 mask;
5055 // uint lod;
5056 // uint granularity;
5057 //};
5058 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5059 assert(builder.isStructType(resultStructType));
5060
5061 //resType (SPIR-V type) contains 6 elements:
5062 //Member 0 must be a Boolean type scalar(LOD),
5063 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5064 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5065 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5066 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5067 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5068 std::vector<spv::Id> members;
5069 members.push_back(resultType());
5070 for (int i = 0; i < 5; i++) {
5071 members.push_back(builder.getContainedTypeId(resultStructType, i));
5072 }
5073 spv::Id resType = builder.makeStructType(members, "ResType");
5074
5075 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005076 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5077 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005078
5079 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5080 for (int i = 0; i < 5; i++) {
5081 builder.clearAccessChain();
5082 builder.setAccessChainLValue(resultStruct);
5083
5084 //Accessing to a struct we created, no coherent flag is set
5085 spv::Builder::AccessChain::CoherentFlags flags;
5086 flags.clear();
5087
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005088 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005089 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5090 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005091 }
5092 return builder.createCompositeExtract(res, resultType(), 0);
5093 }
5094#endif
5095
John Kessenich65336482016-06-16 14:06:26 -06005096 // projective component (might not to move)
5097 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5098 // are divided by the last component of P."
5099 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5100 // unused components will appear after all used components."
5101 if (cracked.proj) {
5102 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5103 int projTargetComp;
5104 switch (sampler.dim) {
5105 case glslang::Esd1D: projTargetComp = 1; break;
5106 case glslang::Esd2D: projTargetComp = 2; break;
5107 case glslang::EsdRect: projTargetComp = 2; break;
5108 default: projTargetComp = projSourceComp; break;
5109 }
5110 // copy the projective coordinate if we have to
5111 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005112 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005113 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005114 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005115 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005116 }
5117 }
5118
John Kessenichf8d1d742019-10-21 06:55:11 -06005119#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005120 // nonprivate
5121 if (imageType.getQualifier().nonprivate) {
5122 params.nonprivate = true;
5123 }
5124
5125 // volatile
5126 if (imageType.getQualifier().volatil) {
5127 params.volatil = true;
5128 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005129#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005130
St0fFa1184dd2018-04-09 21:08:14 +02005131 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005132 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5133 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005134 );
LoopDawg4425f242018-02-18 11:40:01 -07005135
5136 if (components != node->getType().getVectorSize())
5137 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5138
5139 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005140}
5141
5142spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5143{
5144 // Grab the function's pointer from the previously created function
5145 spv::Function* function = functionMap[node->getName().c_str()];
5146 if (! function)
5147 return 0;
5148
5149 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5150 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5151
5152 // See comments in makeFunctions() for details about the semantics for parameter passing.
5153 //
5154 // These imply we need a four step process:
5155 // 1. Evaluate the arguments
5156 // 2. Allocate and make copies of in, out, and inout arguments
5157 // 3. Make the call
5158 // 4. Copy back the results
5159
John Kessenichd3ed90b2018-05-04 11:43:03 -06005160 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005161 std::vector<spv::Builder::AccessChain> lValues;
5162 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005163 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005164 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005165 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005166 // build l-value
5167 builder.clearAccessChain();
5168 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005169 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005170 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005171 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005172 // save l-value
5173 lValues.push_back(builder.getAccessChain());
5174 } else {
5175 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005176 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005177 }
5178 }
5179
5180 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5181 // copy the original into that space.
5182 //
5183 // Also, build up the list of actual arguments to pass in for the call
5184 int lValueCount = 0;
5185 int rValueCount = 0;
5186 std::vector<spv::Id> spvArgs;
5187 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5188 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005189 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005190 builder.setAccessChain(lValues[lValueCount]);
5191 arg = builder.accessChainGetLValue();
5192 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005193 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005194 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005195 arg = builder.createVariable(spv::StorageClassFunction,
5196 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005197 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5198 // need to copy the input into output space
5199 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005200 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005201 builder.clearAccessChain();
5202 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005203 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005204 }
5205 ++lValueCount;
5206 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005207 // process r-value, which involves a copy for a type mismatch
5208 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5209 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5210 builder.clearAccessChain();
5211 builder.setAccessChainLValue(argCopy);
5212 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5213 arg = builder.createLoad(argCopy);
5214 } else
5215 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005216 ++rValueCount;
5217 }
5218 spvArgs.push_back(arg);
5219 }
5220
5221 // 3. Make the call.
5222 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005223 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005224
5225 // 4. Copy back out an "out" arguments.
5226 lValueCount = 0;
5227 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005228 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005229 ++lValueCount;
5230 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005231 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5232 spv::Id copy = builder.createLoad(spvArgs[a]);
5233 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005234 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005235 }
5236 ++lValueCount;
5237 }
5238 }
5239
5240 return result;
5241}
5242
5243// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005244spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005245 spv::Id typeId, spv::Id left, spv::Id right,
5246 glslang::TBasicType typeProxy, bool reduceComparison)
5247{
John Kessenich66011cb2018-03-06 16:12:04 -07005248 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5249 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005250 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005251
5252 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005253 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005254 bool comparison = false;
5255
5256 switch (op) {
5257 case glslang::EOpAdd:
5258 case glslang::EOpAddAssign:
5259 if (isFloat)
5260 binOp = spv::OpFAdd;
5261 else
5262 binOp = spv::OpIAdd;
5263 break;
5264 case glslang::EOpSub:
5265 case glslang::EOpSubAssign:
5266 if (isFloat)
5267 binOp = spv::OpFSub;
5268 else
5269 binOp = spv::OpISub;
5270 break;
5271 case glslang::EOpMul:
5272 case glslang::EOpMulAssign:
5273 if (isFloat)
5274 binOp = spv::OpFMul;
5275 else
5276 binOp = spv::OpIMul;
5277 break;
5278 case glslang::EOpVectorTimesScalar:
5279 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005280 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005281 if (builder.isVector(right))
5282 std::swap(left, right);
5283 assert(builder.isScalar(right));
5284 needMatchingVectors = false;
5285 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005286 } else if (isFloat)
5287 binOp = spv::OpFMul;
5288 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005289 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005290 break;
5291 case glslang::EOpVectorTimesMatrix:
5292 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005293 binOp = spv::OpVectorTimesMatrix;
5294 break;
5295 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005296 binOp = spv::OpMatrixTimesVector;
5297 break;
5298 case glslang::EOpMatrixTimesScalar:
5299 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005300 binOp = spv::OpMatrixTimesScalar;
5301 break;
5302 case glslang::EOpMatrixTimesMatrix:
5303 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005304 binOp = spv::OpMatrixTimesMatrix;
5305 break;
5306 case glslang::EOpOuterProduct:
5307 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005308 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005309 break;
5310
5311 case glslang::EOpDiv:
5312 case glslang::EOpDivAssign:
5313 if (isFloat)
5314 binOp = spv::OpFDiv;
5315 else if (isUnsigned)
5316 binOp = spv::OpUDiv;
5317 else
5318 binOp = spv::OpSDiv;
5319 break;
5320 case glslang::EOpMod:
5321 case glslang::EOpModAssign:
5322 if (isFloat)
5323 binOp = spv::OpFMod;
5324 else if (isUnsigned)
5325 binOp = spv::OpUMod;
5326 else
5327 binOp = spv::OpSMod;
5328 break;
5329 case glslang::EOpRightShift:
5330 case glslang::EOpRightShiftAssign:
5331 if (isUnsigned)
5332 binOp = spv::OpShiftRightLogical;
5333 else
5334 binOp = spv::OpShiftRightArithmetic;
5335 break;
5336 case glslang::EOpLeftShift:
5337 case glslang::EOpLeftShiftAssign:
5338 binOp = spv::OpShiftLeftLogical;
5339 break;
5340 case glslang::EOpAnd:
5341 case glslang::EOpAndAssign:
5342 binOp = spv::OpBitwiseAnd;
5343 break;
5344 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005345 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005346 binOp = spv::OpLogicalAnd;
5347 break;
5348 case glslang::EOpInclusiveOr:
5349 case glslang::EOpInclusiveOrAssign:
5350 binOp = spv::OpBitwiseOr;
5351 break;
5352 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005353 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005354 binOp = spv::OpLogicalOr;
5355 break;
5356 case glslang::EOpExclusiveOr:
5357 case glslang::EOpExclusiveOrAssign:
5358 binOp = spv::OpBitwiseXor;
5359 break;
5360 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005361 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005362 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005363 break;
5364
Ian Romanickb3bd4022019-01-21 08:57:25 -08005365 case glslang::EOpAbsDifference:
5366 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5367 break;
5368
5369 case glslang::EOpAddSaturate:
5370 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5371 break;
5372
5373 case glslang::EOpSubSaturate:
5374 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5375 break;
5376
5377 case glslang::EOpAverage:
5378 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5379 break;
5380
5381 case glslang::EOpAverageRounded:
5382 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5383 break;
5384
5385 case glslang::EOpMul32x16:
5386 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5387 break;
5388
John Kessenich140f3df2015-06-26 16:58:36 -06005389 case glslang::EOpLessThan:
5390 case glslang::EOpGreaterThan:
5391 case glslang::EOpLessThanEqual:
5392 case glslang::EOpGreaterThanEqual:
5393 case glslang::EOpEqual:
5394 case glslang::EOpNotEqual:
5395 case glslang::EOpVectorEqual:
5396 case glslang::EOpVectorNotEqual:
5397 comparison = true;
5398 break;
5399 default:
5400 break;
5401 }
5402
John Kessenich7c1aa102015-10-15 13:29:11 -06005403 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005404 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005405 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005406 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5407 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005408 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005409
5410 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005411 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005412 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005413
qining25262b32016-05-06 17:25:16 -04005414 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005415 decorations.addNoContraction(builder, result);
5416 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005417 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005418 }
5419
5420 if (! comparison)
5421 return 0;
5422
John Kessenich7c1aa102015-10-15 13:29:11 -06005423 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005424
John Kessenich4583b612016-08-07 19:14:22 -06005425 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005426 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5427 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005428 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005429 return result;
5430 }
John Kessenich140f3df2015-06-26 16:58:36 -06005431
5432 switch (op) {
5433 case glslang::EOpLessThan:
5434 if (isFloat)
5435 binOp = spv::OpFOrdLessThan;
5436 else if (isUnsigned)
5437 binOp = spv::OpULessThan;
5438 else
5439 binOp = spv::OpSLessThan;
5440 break;
5441 case glslang::EOpGreaterThan:
5442 if (isFloat)
5443 binOp = spv::OpFOrdGreaterThan;
5444 else if (isUnsigned)
5445 binOp = spv::OpUGreaterThan;
5446 else
5447 binOp = spv::OpSGreaterThan;
5448 break;
5449 case glslang::EOpLessThanEqual:
5450 if (isFloat)
5451 binOp = spv::OpFOrdLessThanEqual;
5452 else if (isUnsigned)
5453 binOp = spv::OpULessThanEqual;
5454 else
5455 binOp = spv::OpSLessThanEqual;
5456 break;
5457 case glslang::EOpGreaterThanEqual:
5458 if (isFloat)
5459 binOp = spv::OpFOrdGreaterThanEqual;
5460 else if (isUnsigned)
5461 binOp = spv::OpUGreaterThanEqual;
5462 else
5463 binOp = spv::OpSGreaterThanEqual;
5464 break;
5465 case glslang::EOpEqual:
5466 case glslang::EOpVectorEqual:
5467 if (isFloat)
5468 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005469 else if (isBool)
5470 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005471 else
5472 binOp = spv::OpIEqual;
5473 break;
5474 case glslang::EOpNotEqual:
5475 case glslang::EOpVectorNotEqual:
5476 if (isFloat)
5477 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005478 else if (isBool)
5479 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005480 else
5481 binOp = spv::OpINotEqual;
5482 break;
5483 default:
5484 break;
5485 }
5486
qining25262b32016-05-06 17:25:16 -04005487 if (binOp != spv::OpNop) {
5488 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005489 decorations.addNoContraction(builder, result);
5490 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005491 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005492 }
John Kessenich140f3df2015-06-26 16:58:36 -06005493
5494 return 0;
5495}
5496
John Kessenich04bb8a02015-12-12 12:28:14 -07005497//
5498// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5499// These can be any of:
5500//
5501// matrix * scalar
5502// scalar * matrix
5503// matrix * matrix linear algebraic
5504// matrix * vector
5505// vector * matrix
5506// matrix * matrix componentwise
5507// matrix op matrix op in {+, -, /}
5508// matrix op scalar op in {+, -, /}
5509// scalar op matrix op in {+, -, /}
5510//
John Kessenichead86222018-03-28 18:01:20 -06005511spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5512 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005513{
5514 bool firstClass = true;
5515
5516 // First, handle first-class matrix operations (* and matrix/scalar)
5517 switch (op) {
5518 case spv::OpFDiv:
5519 if (builder.isMatrix(left) && builder.isScalar(right)) {
5520 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005521 spv::Id resultType = builder.getTypeId(right);
5522 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005523 op = spv::OpMatrixTimesScalar;
5524 } else
5525 firstClass = false;
5526 break;
5527 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005528 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005529 std::swap(left, right);
5530 assert(builder.isScalar(right));
5531 break;
5532 case spv::OpVectorTimesMatrix:
5533 assert(builder.isVector(left));
5534 assert(builder.isMatrix(right));
5535 break;
5536 case spv::OpMatrixTimesVector:
5537 assert(builder.isMatrix(left));
5538 assert(builder.isVector(right));
5539 break;
5540 case spv::OpMatrixTimesMatrix:
5541 assert(builder.isMatrix(left));
5542 assert(builder.isMatrix(right));
5543 break;
5544 default:
5545 firstClass = false;
5546 break;
5547 }
5548
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005549 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5550 firstClass = true;
5551
qining25262b32016-05-06 17:25:16 -04005552 if (firstClass) {
5553 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005554 decorations.addNoContraction(builder, result);
5555 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005556 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005557 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005558
LoopDawg592860c2016-06-09 08:57:35 -06005559 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005560 // The result type of all of them is the same type as the (a) matrix operand.
5561 // The algorithm is to:
5562 // - break the matrix(es) into vectors
5563 // - smear any scalar to a vector
5564 // - do vector operations
5565 // - make a matrix out the vector results
5566 switch (op) {
5567 case spv::OpFAdd:
5568 case spv::OpFSub:
5569 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005570 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005571 case spv::OpFMul:
5572 {
5573 // one time set up...
5574 bool leftMat = builder.isMatrix(left);
5575 bool rightMat = builder.isMatrix(right);
5576 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5577 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5578 spv::Id scalarType = builder.getScalarTypeId(typeId);
5579 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5580 std::vector<spv::Id> results;
5581 spv::Id smearVec = spv::NoResult;
5582 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005583 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005584 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005585 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005586
5587 // do each vector op
5588 for (unsigned int c = 0; c < numCols; ++c) {
5589 std::vector<unsigned int> indexes;
5590 indexes.push_back(c);
5591 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5592 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005593 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005594 decorations.addNoContraction(builder, result);
5595 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005596 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005597 }
5598
5599 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005600 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005601 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005602 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005603 }
5604 default:
5605 assert(0);
5606 return spv::NoResult;
5607 }
5608}
5609
John Kessenichead86222018-03-28 18:01:20 -06005610spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005611 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005612{
5613 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005614 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005615 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005616 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5617 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005618
5619 switch (op) {
5620 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005621 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005622 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005623 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005624 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005625 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005626 unaryOp = spv::OpSNegate;
5627 break;
5628
5629 case glslang::EOpLogicalNot:
5630 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005631 unaryOp = spv::OpLogicalNot;
5632 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005633 case glslang::EOpBitwiseNot:
5634 unaryOp = spv::OpNot;
5635 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005636
John Kessenich140f3df2015-06-26 16:58:36 -06005637 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005638 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005639 break;
5640 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005641 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005642 break;
5643 case glslang::EOpTranspose:
5644 unaryOp = spv::OpTranspose;
5645 break;
5646
5647 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005648 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005649 break;
5650 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005651 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005652 break;
5653 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005654 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005655 break;
5656 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005657 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005658 break;
5659 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005660 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005661 break;
5662 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005663 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005664 break;
5665 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005666 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005667 break;
5668 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005669 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005670 break;
5671
5672 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005673 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005674 break;
5675 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005676 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005677 break;
5678 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005679 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005680 break;
5681 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005682 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005683 break;
5684 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005685 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005686 break;
5687 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005688 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005689 break;
5690
5691 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005692 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005693 break;
5694 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005695 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005696 break;
5697
5698 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005699 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005700 break;
5701 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005702 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005703 break;
5704 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005705 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005706 break;
5707 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005708 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005709 break;
5710 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005711 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005712 break;
5713 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005714 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005715 break;
5716
5717 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005718 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005719 break;
5720 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005721 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005722 break;
5723 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005724 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005725 break;
5726 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005727 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005728 break;
5729 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005730 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005731 break;
5732 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005733 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005734 break;
5735
5736 case glslang::EOpIsNan:
5737 unaryOp = spv::OpIsNan;
5738 break;
5739 case glslang::EOpIsInf:
5740 unaryOp = spv::OpIsInf;
5741 break;
LoopDawg592860c2016-06-09 08:57:35 -06005742 case glslang::EOpIsFinite:
5743 unaryOp = spv::OpIsFinite;
5744 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005745
Rex Xucbc426e2015-12-15 16:03:10 +08005746 case glslang::EOpFloatBitsToInt:
5747 case glslang::EOpFloatBitsToUint:
5748 case glslang::EOpIntBitsToFloat:
5749 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005750 case glslang::EOpDoubleBitsToInt64:
5751 case glslang::EOpDoubleBitsToUint64:
5752 case glslang::EOpInt64BitsToDouble:
5753 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005754 case glslang::EOpFloat16BitsToInt16:
5755 case glslang::EOpFloat16BitsToUint16:
5756 case glslang::EOpInt16BitsToFloat16:
5757 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005758 unaryOp = spv::OpBitcast;
5759 break;
5760
John Kessenich140f3df2015-06-26 16:58:36 -06005761 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005762 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005763 break;
5764 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005765 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005766 break;
5767 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005768 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005769 break;
5770 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005771 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005772 break;
5773 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005774 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005775 break;
5776 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005777 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005778 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005779#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005780 case glslang::EOpPackSnorm4x8:
5781 libCall = spv::GLSLstd450PackSnorm4x8;
5782 break;
5783 case glslang::EOpUnpackSnorm4x8:
5784 libCall = spv::GLSLstd450UnpackSnorm4x8;
5785 break;
5786 case glslang::EOpPackUnorm4x8:
5787 libCall = spv::GLSLstd450PackUnorm4x8;
5788 break;
5789 case glslang::EOpUnpackUnorm4x8:
5790 libCall = spv::GLSLstd450UnpackUnorm4x8;
5791 break;
5792 case glslang::EOpPackDouble2x32:
5793 libCall = spv::GLSLstd450PackDouble2x32;
5794 break;
5795 case glslang::EOpUnpackDouble2x32:
5796 libCall = spv::GLSLstd450UnpackDouble2x32;
5797 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005798#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005799
Rex Xu8ff43de2016-04-22 16:51:45 +08005800 case glslang::EOpPackInt2x32:
5801 case glslang::EOpUnpackInt2x32:
5802 case glslang::EOpPackUint2x32:
5803 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005804 case glslang::EOpPack16:
5805 case glslang::EOpPack32:
5806 case glslang::EOpPack64:
5807 case glslang::EOpUnpack32:
5808 case glslang::EOpUnpack16:
5809 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005810 case glslang::EOpPackInt2x16:
5811 case glslang::EOpUnpackInt2x16:
5812 case glslang::EOpPackUint2x16:
5813 case glslang::EOpUnpackUint2x16:
5814 case glslang::EOpPackInt4x16:
5815 case glslang::EOpUnpackInt4x16:
5816 case glslang::EOpPackUint4x16:
5817 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005818 case glslang::EOpPackFloat2x16:
5819 case glslang::EOpUnpackFloat2x16:
5820 unaryOp = spv::OpBitcast;
5821 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005822
John Kessenich140f3df2015-06-26 16:58:36 -06005823 case glslang::EOpDPdx:
5824 unaryOp = spv::OpDPdx;
5825 break;
5826 case glslang::EOpDPdy:
5827 unaryOp = spv::OpDPdy;
5828 break;
5829 case glslang::EOpFwidth:
5830 unaryOp = spv::OpFwidth;
5831 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005832
John Kessenich140f3df2015-06-26 16:58:36 -06005833 case glslang::EOpAny:
5834 unaryOp = spv::OpAny;
5835 break;
5836 case glslang::EOpAll:
5837 unaryOp = spv::OpAll;
5838 break;
5839
5840 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005841 if (isFloat)
5842 libCall = spv::GLSLstd450FAbs;
5843 else
5844 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005847 if (isFloat)
5848 libCall = spv::GLSLstd450FSign;
5849 else
5850 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005851 break;
5852
John Kessenicha28f7a72019-08-06 07:00:58 -06005853#ifndef GLSLANG_WEB
5854 case glslang::EOpDPdxFine:
5855 unaryOp = spv::OpDPdxFine;
5856 break;
5857 case glslang::EOpDPdyFine:
5858 unaryOp = spv::OpDPdyFine;
5859 break;
5860 case glslang::EOpFwidthFine:
5861 unaryOp = spv::OpFwidthFine;
5862 break;
5863 case glslang::EOpDPdxCoarse:
5864 unaryOp = spv::OpDPdxCoarse;
5865 break;
5866 case glslang::EOpDPdyCoarse:
5867 unaryOp = spv::OpDPdyCoarse;
5868 break;
5869 case glslang::EOpFwidthCoarse:
5870 unaryOp = spv::OpFwidthCoarse;
5871 break;
5872 case glslang::EOpInterpolateAtCentroid:
5873 if (typeProxy == glslang::EbtFloat16)
5874 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5875 libCall = spv::GLSLstd450InterpolateAtCentroid;
5876 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005877 case glslang::EOpAtomicCounterIncrement:
5878 case glslang::EOpAtomicCounterDecrement:
5879 case glslang::EOpAtomicCounter:
5880 {
5881 // Handle all of the atomics in one place, in createAtomicOperation()
5882 std::vector<spv::Id> operands;
5883 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005884 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005885 }
5886
John Kessenichfc51d282015-08-19 13:34:18 -06005887 case glslang::EOpBitFieldReverse:
5888 unaryOp = spv::OpBitReverse;
5889 break;
5890 case glslang::EOpBitCount:
5891 unaryOp = spv::OpBitCount;
5892 break;
5893 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005894 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005895 break;
5896 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005897 if (isUnsigned)
5898 libCall = spv::GLSLstd450FindUMsb;
5899 else
5900 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005901 break;
5902
Ian Romanickb3bd4022019-01-21 08:57:25 -08005903 case glslang::EOpCountLeadingZeros:
5904 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5905 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5906 unaryOp = spv::OpUCountLeadingZerosINTEL;
5907 break;
5908
5909 case glslang::EOpCountTrailingZeros:
5910 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5911 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5912 unaryOp = spv::OpUCountTrailingZerosINTEL;
5913 break;
5914
Rex Xu574ab042016-04-14 16:53:07 +08005915 case glslang::EOpBallot:
5916 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005917 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005918 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005919 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005920 case glslang::EOpMinInvocations:
5921 case glslang::EOpMaxInvocations:
5922 case glslang::EOpAddInvocations:
5923 case glslang::EOpMinInvocationsNonUniform:
5924 case glslang::EOpMaxInvocationsNonUniform:
5925 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005926 case glslang::EOpMinInvocationsInclusiveScan:
5927 case glslang::EOpMaxInvocationsInclusiveScan:
5928 case glslang::EOpAddInvocationsInclusiveScan:
5929 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5930 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5931 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5932 case glslang::EOpMinInvocationsExclusiveScan:
5933 case glslang::EOpMaxInvocationsExclusiveScan:
5934 case glslang::EOpAddInvocationsExclusiveScan:
5935 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5936 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5937 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005938 {
5939 std::vector<spv::Id> operands;
5940 operands.push_back(operand);
5941 return createInvocationsOperation(op, typeId, operands, typeProxy);
5942 }
John Kessenich66011cb2018-03-06 16:12:04 -07005943 case glslang::EOpSubgroupAll:
5944 case glslang::EOpSubgroupAny:
5945 case glslang::EOpSubgroupAllEqual:
5946 case glslang::EOpSubgroupBroadcastFirst:
5947 case glslang::EOpSubgroupBallot:
5948 case glslang::EOpSubgroupInverseBallot:
5949 case glslang::EOpSubgroupBallotBitCount:
5950 case glslang::EOpSubgroupBallotInclusiveBitCount:
5951 case glslang::EOpSubgroupBallotExclusiveBitCount:
5952 case glslang::EOpSubgroupBallotFindLSB:
5953 case glslang::EOpSubgroupBallotFindMSB:
5954 case glslang::EOpSubgroupAdd:
5955 case glslang::EOpSubgroupMul:
5956 case glslang::EOpSubgroupMin:
5957 case glslang::EOpSubgroupMax:
5958 case glslang::EOpSubgroupAnd:
5959 case glslang::EOpSubgroupOr:
5960 case glslang::EOpSubgroupXor:
5961 case glslang::EOpSubgroupInclusiveAdd:
5962 case glslang::EOpSubgroupInclusiveMul:
5963 case glslang::EOpSubgroupInclusiveMin:
5964 case glslang::EOpSubgroupInclusiveMax:
5965 case glslang::EOpSubgroupInclusiveAnd:
5966 case glslang::EOpSubgroupInclusiveOr:
5967 case glslang::EOpSubgroupInclusiveXor:
5968 case glslang::EOpSubgroupExclusiveAdd:
5969 case glslang::EOpSubgroupExclusiveMul:
5970 case glslang::EOpSubgroupExclusiveMin:
5971 case glslang::EOpSubgroupExclusiveMax:
5972 case glslang::EOpSubgroupExclusiveAnd:
5973 case glslang::EOpSubgroupExclusiveOr:
5974 case glslang::EOpSubgroupExclusiveXor:
5975 case glslang::EOpSubgroupQuadSwapHorizontal:
5976 case glslang::EOpSubgroupQuadSwapVertical:
5977 case glslang::EOpSubgroupQuadSwapDiagonal: {
5978 std::vector<spv::Id> operands;
5979 operands.push_back(operand);
5980 return createSubgroupOperation(op, typeId, operands, typeProxy);
5981 }
Rex Xu9d93a232016-05-05 12:30:44 +08005982 case glslang::EOpMbcnt:
5983 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5984 libCall = spv::MbcntAMD;
5985 break;
5986
5987 case glslang::EOpCubeFaceIndex:
5988 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5989 libCall = spv::CubeFaceIndexAMD;
5990 break;
5991
5992 case glslang::EOpCubeFaceCoord:
5993 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5994 libCall = spv::CubeFaceCoordAMD;
5995 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005996 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005997 unaryOp = spv::OpGroupNonUniformPartitionNV;
5998 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005999 case glslang::EOpConstructReference:
6000 unaryOp = spv::OpBitcast;
6001 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006002#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006003
6004 case glslang::EOpCopyObject:
6005 unaryOp = spv::OpCopyObject;
6006 break;
6007
John Kessenich140f3df2015-06-26 16:58:36 -06006008 default:
6009 return 0;
6010 }
6011
6012 spv::Id id;
6013 if (libCall >= 0) {
6014 std::vector<spv::Id> args;
6015 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006016 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006017 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006018 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006019 }
John Kessenich140f3df2015-06-26 16:58:36 -06006020
John Kessenichb9197c82019-08-11 07:41:45 -06006021 decorations.addNoContraction(builder, id);
6022 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006023 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006024}
6025
John Kessenich7a53f762016-01-20 11:19:27 -07006026// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006027spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6028 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006029{
6030 // Handle unary operations vector by vector.
6031 // The result type is the same type as the original type.
6032 // The algorithm is to:
6033 // - break the matrix into vectors
6034 // - apply the operation to each vector
6035 // - make a matrix out the vector results
6036
6037 // get the types sorted out
6038 int numCols = builder.getNumColumns(operand);
6039 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006040 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6041 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006042 std::vector<spv::Id> results;
6043
6044 // do each vector op
6045 for (int c = 0; c < numCols; ++c) {
6046 std::vector<unsigned int> indexes;
6047 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006048 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6049 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006050 decorations.addNoContraction(builder, destVec);
6051 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006052 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006053 }
6054
6055 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006056 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006057 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006058 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006059}
6060
John Kessenichad7645f2018-06-04 19:11:25 -06006061// For converting integers where both the bitwidth and the signedness could
6062// change, but only do the width change here. The caller is still responsible
6063// for the signedness conversion.
6064spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006065{
John Kessenichad7645f2018-06-04 19:11:25 -06006066 // Get the result type width, based on the type to convert to.
6067 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006068 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006069 case glslang::EOpConvInt16ToUint8:
6070 case glslang::EOpConvIntToUint8:
6071 case glslang::EOpConvInt64ToUint8:
6072 case glslang::EOpConvUint16ToInt8:
6073 case glslang::EOpConvUintToInt8:
6074 case glslang::EOpConvUint64ToInt8:
6075 width = 8;
6076 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006077 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006078 case glslang::EOpConvIntToUint16:
6079 case glslang::EOpConvInt64ToUint16:
6080 case glslang::EOpConvUint8ToInt16:
6081 case glslang::EOpConvUintToInt16:
6082 case glslang::EOpConvUint64ToInt16:
6083 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006084 break;
6085 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006086 case glslang::EOpConvInt16ToUint:
6087 case glslang::EOpConvInt64ToUint:
6088 case glslang::EOpConvUint8ToInt:
6089 case glslang::EOpConvUint16ToInt:
6090 case glslang::EOpConvUint64ToInt:
6091 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006092 break;
6093 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006094 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006095 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006096 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006097 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006098 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006099 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006100 break;
6101
6102 default:
6103 assert(false && "Default missing");
6104 break;
6105 }
6106
John Kessenichad7645f2018-06-04 19:11:25 -06006107 // Get the conversion operation and result type,
6108 // based on the target width, but the source type.
6109 spv::Id type = spv::NoType;
6110 spv::Op convOp = spv::OpNop;
6111 switch(op) {
6112 case glslang::EOpConvInt8ToUint16:
6113 case glslang::EOpConvInt8ToUint:
6114 case glslang::EOpConvInt8ToUint64:
6115 case glslang::EOpConvInt16ToUint8:
6116 case glslang::EOpConvInt16ToUint:
6117 case glslang::EOpConvInt16ToUint64:
6118 case glslang::EOpConvIntToUint8:
6119 case glslang::EOpConvIntToUint16:
6120 case glslang::EOpConvIntToUint64:
6121 case glslang::EOpConvInt64ToUint8:
6122 case glslang::EOpConvInt64ToUint16:
6123 case glslang::EOpConvInt64ToUint:
6124 convOp = spv::OpSConvert;
6125 type = builder.makeIntType(width);
6126 break;
6127 default:
6128 convOp = spv::OpUConvert;
6129 type = builder.makeUintType(width);
6130 break;
6131 }
6132
John Kessenich66011cb2018-03-06 16:12:04 -07006133 if (vectorSize > 0)
6134 type = builder.makeVectorType(type, vectorSize);
6135
John Kessenichad7645f2018-06-04 19:11:25 -06006136 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006137}
6138
John Kessenichead86222018-03-28 18:01:20 -06006139spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6140 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006141{
6142 spv::Op convOp = spv::OpNop;
6143 spv::Id zero = 0;
6144 spv::Id one = 0;
6145
6146 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6147
6148 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006149 case glslang::EOpConvIntToBool:
6150 case glslang::EOpConvUintToBool:
6151 zero = builder.makeUintConstant(0);
6152 zero = makeSmearedConstant(zero, vectorSize);
6153 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006154 case glslang::EOpConvFloatToBool:
6155 zero = builder.makeFloatConstant(0.0F);
6156 zero = makeSmearedConstant(zero, vectorSize);
6157 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006158 case glslang::EOpConvBoolToFloat:
6159 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006160 zero = builder.makeFloatConstant(0.0F);
6161 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006162 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006163
John Kessenich140f3df2015-06-26 16:58:36 -06006164 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006165 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006166#ifndef GLSLANG_WEB
6167 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006168 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006169 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006170 } else
6171#endif
6172 {
6173 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006174 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006175 }
Rex Xucabbb782017-03-24 13:41:14 +08006176
John Kessenich140f3df2015-06-26 16:58:36 -06006177 convOp = spv::OpSelect;
6178 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006179
John Kessenich140f3df2015-06-26 16:58:36 -06006180 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006181 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006182#ifndef GLSLANG_WEB
6183 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006184 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006185 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006186 } else
6187#endif
6188 {
6189 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006190 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006191 }
Rex Xucabbb782017-03-24 13:41:14 +08006192
John Kessenich140f3df2015-06-26 16:58:36 -06006193 convOp = spv::OpSelect;
6194 break;
6195
John Kessenich66011cb2018-03-06 16:12:04 -07006196 case glslang::EOpConvInt8ToFloat16:
6197 case glslang::EOpConvInt8ToFloat:
6198 case glslang::EOpConvInt8ToDouble:
6199 case glslang::EOpConvInt16ToFloat16:
6200 case glslang::EOpConvInt16ToFloat:
6201 case glslang::EOpConvInt16ToDouble:
6202 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006203 case glslang::EOpConvIntToFloat:
6204 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006205 case glslang::EOpConvInt64ToFloat:
6206 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006207 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006208 convOp = spv::OpConvertSToF;
6209 break;
6210
John Kessenich66011cb2018-03-06 16:12:04 -07006211 case glslang::EOpConvUint8ToFloat16:
6212 case glslang::EOpConvUint8ToFloat:
6213 case glslang::EOpConvUint8ToDouble:
6214 case glslang::EOpConvUint16ToFloat16:
6215 case glslang::EOpConvUint16ToFloat:
6216 case glslang::EOpConvUint16ToDouble:
6217 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006218 case glslang::EOpConvUintToFloat:
6219 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006220 case glslang::EOpConvUint64ToFloat:
6221 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006222 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006223 convOp = spv::OpConvertUToF;
6224 break;
6225
John Kessenich66011cb2018-03-06 16:12:04 -07006226 case glslang::EOpConvFloat16ToInt8:
6227 case glslang::EOpConvFloatToInt8:
6228 case glslang::EOpConvDoubleToInt8:
6229 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006230 case glslang::EOpConvFloatToInt16:
6231 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006232 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006233 case glslang::EOpConvFloatToInt:
6234 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006235 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006236 case glslang::EOpConvFloatToInt64:
6237 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006238 convOp = spv::OpConvertFToS;
6239 break;
6240
John Kessenich66011cb2018-03-06 16:12:04 -07006241 case glslang::EOpConvUint8ToInt8:
6242 case glslang::EOpConvInt8ToUint8:
6243 case glslang::EOpConvUint16ToInt16:
6244 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006245 case glslang::EOpConvUintToInt:
6246 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006247 case glslang::EOpConvUint64ToInt64:
6248 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006249 if (builder.isInSpecConstCodeGenMode()) {
6250 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006251#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006252 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6253 zero = builder.makeUint8Constant(0);
6254 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006255 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006256 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6257 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006258 } else
6259#endif
6260 {
Rex Xucabbb782017-03-24 13:41:14 +08006261 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006262 }
qining189b2032016-04-12 23:16:20 -04006263 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006264 // Use OpIAdd, instead of OpBitcast to do the conversion when
6265 // generating for OpSpecConstantOp instruction.
6266 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6267 }
6268 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006269 convOp = spv::OpBitcast;
6270 break;
6271
John Kessenich66011cb2018-03-06 16:12:04 -07006272 case glslang::EOpConvFloat16ToUint8:
6273 case glslang::EOpConvFloatToUint8:
6274 case glslang::EOpConvDoubleToUint8:
6275 case glslang::EOpConvFloat16ToUint16:
6276 case glslang::EOpConvFloatToUint16:
6277 case glslang::EOpConvDoubleToUint16:
6278 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006279 case glslang::EOpConvFloatToUint:
6280 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006281 case glslang::EOpConvFloatToUint64:
6282 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006283 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006284 convOp = spv::OpConvertFToU;
6285 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006286
John Kessenich39697cd2019-08-08 10:35:51 -06006287#ifndef GLSLANG_WEB
6288 case glslang::EOpConvInt8ToBool:
6289 case glslang::EOpConvUint8ToBool:
6290 zero = builder.makeUint8Constant(0);
6291 zero = makeSmearedConstant(zero, vectorSize);
6292 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6293 case glslang::EOpConvInt16ToBool:
6294 case glslang::EOpConvUint16ToBool:
6295 zero = builder.makeUint16Constant(0);
6296 zero = makeSmearedConstant(zero, vectorSize);
6297 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6298 case glslang::EOpConvInt64ToBool:
6299 case glslang::EOpConvUint64ToBool:
6300 zero = builder.makeUint64Constant(0);
6301 zero = makeSmearedConstant(zero, vectorSize);
6302 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6303 case glslang::EOpConvDoubleToBool:
6304 zero = builder.makeDoubleConstant(0.0);
6305 zero = makeSmearedConstant(zero, vectorSize);
6306 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6307 case glslang::EOpConvFloat16ToBool:
6308 zero = builder.makeFloat16Constant(0.0F);
6309 zero = makeSmearedConstant(zero, vectorSize);
6310 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6311 case glslang::EOpConvBoolToDouble:
6312 convOp = spv::OpSelect;
6313 zero = builder.makeDoubleConstant(0.0);
6314 one = builder.makeDoubleConstant(1.0);
6315 break;
6316 case glslang::EOpConvBoolToFloat16:
6317 convOp = spv::OpSelect;
6318 zero = builder.makeFloat16Constant(0.0F);
6319 one = builder.makeFloat16Constant(1.0F);
6320 break;
6321 case glslang::EOpConvBoolToInt8:
6322 zero = builder.makeInt8Constant(0);
6323 one = builder.makeInt8Constant(1);
6324 convOp = spv::OpSelect;
6325 break;
6326 case glslang::EOpConvBoolToUint8:
6327 zero = builder.makeUint8Constant(0);
6328 one = builder.makeUint8Constant(1);
6329 convOp = spv::OpSelect;
6330 break;
6331 case glslang::EOpConvBoolToInt16:
6332 zero = builder.makeInt16Constant(0);
6333 one = builder.makeInt16Constant(1);
6334 convOp = spv::OpSelect;
6335 break;
6336 case glslang::EOpConvBoolToUint16:
6337 zero = builder.makeUint16Constant(0);
6338 one = builder.makeUint16Constant(1);
6339 convOp = spv::OpSelect;
6340 break;
6341 case glslang::EOpConvDoubleToFloat:
6342 case glslang::EOpConvFloatToDouble:
6343 case glslang::EOpConvDoubleToFloat16:
6344 case glslang::EOpConvFloat16ToDouble:
6345 case glslang::EOpConvFloatToFloat16:
6346 case glslang::EOpConvFloat16ToFloat:
6347 convOp = spv::OpFConvert;
6348 if (builder.isMatrixType(destType))
6349 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6350 break;
6351
John Kessenich66011cb2018-03-06 16:12:04 -07006352 case glslang::EOpConvInt8ToInt16:
6353 case glslang::EOpConvInt8ToInt:
6354 case glslang::EOpConvInt8ToInt64:
6355 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006356 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006357 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006358 case glslang::EOpConvIntToInt8:
6359 case glslang::EOpConvIntToInt16:
6360 case glslang::EOpConvIntToInt64:
6361 case glslang::EOpConvInt64ToInt8:
6362 case glslang::EOpConvInt64ToInt16:
6363 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006364 convOp = spv::OpSConvert;
6365 break;
6366
John Kessenich66011cb2018-03-06 16:12:04 -07006367 case glslang::EOpConvUint8ToUint16:
6368 case glslang::EOpConvUint8ToUint:
6369 case glslang::EOpConvUint8ToUint64:
6370 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006371 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006372 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006373 case glslang::EOpConvUintToUint8:
6374 case glslang::EOpConvUintToUint16:
6375 case glslang::EOpConvUintToUint64:
6376 case glslang::EOpConvUint64ToUint8:
6377 case glslang::EOpConvUint64ToUint16:
6378 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006379 convOp = spv::OpUConvert;
6380 break;
6381
John Kessenich66011cb2018-03-06 16:12:04 -07006382 case glslang::EOpConvInt8ToUint16:
6383 case glslang::EOpConvInt8ToUint:
6384 case glslang::EOpConvInt8ToUint64:
6385 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006386 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006387 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006388 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006389 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006390 case glslang::EOpConvIntToUint64:
6391 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006392 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006393 case glslang::EOpConvInt64ToUint:
6394 case glslang::EOpConvUint8ToInt16:
6395 case glslang::EOpConvUint8ToInt:
6396 case glslang::EOpConvUint8ToInt64:
6397 case glslang::EOpConvUint16ToInt8:
6398 case glslang::EOpConvUint16ToInt:
6399 case glslang::EOpConvUint16ToInt64:
6400 case glslang::EOpConvUintToInt8:
6401 case glslang::EOpConvUintToInt16:
6402 case glslang::EOpConvUintToInt64:
6403 case glslang::EOpConvUint64ToInt8:
6404 case glslang::EOpConvUint64ToInt16:
6405 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006406 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006407 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006408
6409 if (builder.isInSpecConstCodeGenMode()) {
6410 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006411 switch(op) {
6412 case glslang::EOpConvInt16ToUint8:
6413 case glslang::EOpConvIntToUint8:
6414 case glslang::EOpConvInt64ToUint8:
6415 case glslang::EOpConvUint16ToInt8:
6416 case glslang::EOpConvUintToInt8:
6417 case glslang::EOpConvUint64ToInt8:
6418 zero = builder.makeUint8Constant(0);
6419 break;
6420 case glslang::EOpConvInt8ToUint16:
6421 case glslang::EOpConvIntToUint16:
6422 case glslang::EOpConvInt64ToUint16:
6423 case glslang::EOpConvUint8ToInt16:
6424 case glslang::EOpConvUintToInt16:
6425 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006426 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006427 break;
6428 case glslang::EOpConvInt8ToUint:
6429 case glslang::EOpConvInt16ToUint:
6430 case glslang::EOpConvInt64ToUint:
6431 case glslang::EOpConvUint8ToInt:
6432 case glslang::EOpConvUint16ToInt:
6433 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006434 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006435 break;
6436 case glslang::EOpConvInt8ToUint64:
6437 case glslang::EOpConvInt16ToUint64:
6438 case glslang::EOpConvIntToUint64:
6439 case glslang::EOpConvUint8ToInt64:
6440 case glslang::EOpConvUint16ToInt64:
6441 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006442 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006443 break;
6444 default:
6445 assert(false && "Default missing");
6446 break;
6447 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006448 zero = makeSmearedConstant(zero, vectorSize);
6449 // Use OpIAdd, instead of OpBitcast to do the conversion when
6450 // generating for OpSpecConstantOp instruction.
6451 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6452 }
6453 // For normal run-time conversion instruction, use OpBitcast.
6454 convOp = spv::OpBitcast;
6455 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006456 case glslang::EOpConvUint64ToPtr:
6457 convOp = spv::OpConvertUToPtr;
6458 break;
6459 case glslang::EOpConvPtrToUint64:
6460 convOp = spv::OpConvertPtrToU;
6461 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006462 case glslang::EOpConvPtrToUvec2:
6463 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006464 if (builder.isVector(operand))
6465 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6466 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006467 convOp = spv::OpBitcast;
6468 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006469#endif
6470
John Kessenich140f3df2015-06-26 16:58:36 -06006471 default:
6472 break;
6473 }
6474
6475 spv::Id result = 0;
6476 if (convOp == spv::OpNop)
6477 return result;
6478
6479 if (convOp == spv::OpSelect) {
6480 zero = makeSmearedConstant(zero, vectorSize);
6481 one = makeSmearedConstant(one, vectorSize);
6482 result = builder.createTriOp(convOp, destType, operand, one, zero);
6483 } else
6484 result = builder.createUnaryOp(convOp, destType, operand);
6485
John Kessenichead86222018-03-28 18:01:20 -06006486 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006487 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006488 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006489}
6490
6491spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6492{
6493 if (vectorSize == 0)
6494 return constant;
6495
6496 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6497 std::vector<spv::Id> components;
6498 for (int c = 0; c < vectorSize; ++c)
6499 components.push_back(constant);
6500 return builder.makeCompositeConstant(vectorTypeId, components);
6501}
6502
John Kessenich426394d2015-07-23 10:22:48 -06006503// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006504spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6505 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6506 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006507{
6508 spv::Op opCode = spv::OpNop;
6509
6510 switch (op) {
6511 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006512 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006513 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006514 opCode = spv::OpAtomicIAdd;
6515 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006516 case glslang::EOpAtomicCounterSubtract:
6517 opCode = spv::OpAtomicISub;
6518 break;
John Kessenich426394d2015-07-23 10:22:48 -06006519 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006520 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006521 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006522 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6523 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006524 break;
6525 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006526 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006527 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006528 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6529 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006530 break;
6531 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006532 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006533 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006534 opCode = spv::OpAtomicAnd;
6535 break;
6536 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006537 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006538 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006539 opCode = spv::OpAtomicOr;
6540 break;
6541 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006542 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006543 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006544 opCode = spv::OpAtomicXor;
6545 break;
6546 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006547 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006548 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006549 opCode = spv::OpAtomicExchange;
6550 break;
6551 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006552 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006553 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006554 opCode = spv::OpAtomicCompareExchange;
6555 break;
6556 case glslang::EOpAtomicCounterIncrement:
6557 opCode = spv::OpAtomicIIncrement;
6558 break;
6559 case glslang::EOpAtomicCounterDecrement:
6560 opCode = spv::OpAtomicIDecrement;
6561 break;
6562 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006563 case glslang::EOpImageAtomicLoad:
6564 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006565 opCode = spv::OpAtomicLoad;
6566 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006567 case glslang::EOpAtomicStore:
6568 case glslang::EOpImageAtomicStore:
6569 opCode = spv::OpAtomicStore;
6570 break;
John Kessenich426394d2015-07-23 10:22:48 -06006571 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006572 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006573 break;
6574 }
6575
Rex Xue8fe8b02017-09-26 15:42:56 +08006576 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6577 builder.addCapability(spv::CapabilityInt64Atomics);
6578
John Kessenich426394d2015-07-23 10:22:48 -06006579 // Sort out the operands
6580 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006581 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006582 // - compare-exchange swaps the value and comparator
6583 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006584 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006585 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6586 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6587 spv::Id scopeId;
6588 if (glslangIntermediate->usingVulkanMemoryModel()) {
6589 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6590 } else {
6591 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6592 }
6593 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006594 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6595 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006596 spv::MemorySemanticsVolatileMask :
6597 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006598 spv::Id semanticsId2 = semanticsId;
6599
6600 pointerId = operands[0];
6601 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6602 // no additional operands
6603 } else if (opCode == spv::OpAtomicCompareExchange) {
6604 compareId = operands[1];
6605 valueId = operands[2];
6606 if (operands.size() > 3) {
6607 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006608 semanticsId = builder.makeUintConstant(
6609 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6610 semanticsId2 = builder.makeUintConstant(
6611 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006612 }
6613 } else if (opCode == spv::OpAtomicLoad) {
6614 if (operands.size() > 1) {
6615 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006616 semanticsId = builder.makeUintConstant(
6617 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006618 }
6619 } else {
6620 // atomic store or RMW
6621 valueId = operands[1];
6622 if (operands.size() > 2) {
6623 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006624 semanticsId = builder.makeUintConstant
6625 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006626 }
Rex Xu04db3f52015-09-16 11:44:02 +08006627 }
John Kessenich426394d2015-07-23 10:22:48 -06006628
Jeff Bolz36831c92018-09-05 10:11:41 -05006629 // Check for capabilities
6630 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006631 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6632 spv::MemorySemanticsMakeVisibleKHRMask |
6633 spv::MemorySemanticsOutputMemoryKHRMask |
6634 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006635 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6636 }
John Kessenich426394d2015-07-23 10:22:48 -06006637
Jeff Bolz36831c92018-09-05 10:11:41 -05006638 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6639 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6640 }
John Kessenich48d6e792017-10-06 21:21:48 -06006641
Jeff Bolz36831c92018-09-05 10:11:41 -05006642 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6643 spvAtomicOperands.push_back(pointerId);
6644 spvAtomicOperands.push_back(scopeId);
6645 spvAtomicOperands.push_back(semanticsId);
6646 if (opCode == spv::OpAtomicCompareExchange) {
6647 spvAtomicOperands.push_back(semanticsId2);
6648 spvAtomicOperands.push_back(valueId);
6649 spvAtomicOperands.push_back(compareId);
6650 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6651 spvAtomicOperands.push_back(valueId);
6652 }
John Kessenich48d6e792017-10-06 21:21:48 -06006653
Jeff Bolz36831c92018-09-05 10:11:41 -05006654 if (opCode == spv::OpAtomicStore) {
6655 builder.createNoResultOp(opCode, spvAtomicOperands);
6656 return 0;
6657 } else {
6658 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6659
6660 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6661 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6662 if (op == glslang::EOpAtomicCounterDecrement)
6663 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6664
6665 return resultId;
6666 }
John Kessenich426394d2015-07-23 10:22:48 -06006667}
6668
John Kessenich91cef522016-05-05 16:45:40 -06006669// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006670spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6671 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006672{
John Kessenich66011cb2018-03-06 16:12:04 -07006673 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6674 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006675
Rex Xu51596642016-09-21 18:56:12 +08006676 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006677 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006678 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6679
chaocf200da82016-12-20 12:44:35 -08006680 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6681 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006682 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6683 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006684 } else if (op == glslang::EOpAnyInvocation ||
6685 op == glslang::EOpAllInvocations ||
6686 op == glslang::EOpAllInvocationsEqual) {
6687 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6688 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006689 } else {
6690 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006691 if (op == glslang::EOpMinInvocationsNonUniform ||
6692 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006693 op == glslang::EOpAddInvocationsNonUniform ||
6694 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6695 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6696 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6697 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6698 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6699 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006700 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006701
Rex Xu430ef402016-10-14 17:22:23 +08006702 switch (op) {
6703 case glslang::EOpMinInvocations:
6704 case glslang::EOpMaxInvocations:
6705 case glslang::EOpAddInvocations:
6706 case glslang::EOpMinInvocationsNonUniform:
6707 case glslang::EOpMaxInvocationsNonUniform:
6708 case glslang::EOpAddInvocationsNonUniform:
6709 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006710 break;
6711 case glslang::EOpMinInvocationsInclusiveScan:
6712 case glslang::EOpMaxInvocationsInclusiveScan:
6713 case glslang::EOpAddInvocationsInclusiveScan:
6714 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6715 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6716 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6717 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006718 break;
6719 case glslang::EOpMinInvocationsExclusiveScan:
6720 case glslang::EOpMaxInvocationsExclusiveScan:
6721 case glslang::EOpAddInvocationsExclusiveScan:
6722 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6723 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6724 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6725 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006726 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006727 default:
6728 break;
Rex Xu430ef402016-10-14 17:22:23 +08006729 }
John Kessenich149afc32018-08-14 13:31:43 -06006730 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6731 spvGroupOperands.push_back(scope);
6732 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006733 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006734 spvGroupOperands.push_back(groupOp);
6735 }
Rex Xu51596642016-09-21 18:56:12 +08006736 }
6737
John Kessenich149afc32018-08-14 13:31:43 -06006738 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6739 spv::IdImmediate op = { true, *opIt };
6740 spvGroupOperands.push_back(op);
6741 }
John Kessenich91cef522016-05-05 16:45:40 -06006742
6743 switch (op) {
6744 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006745 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006746 break;
John Kessenich91cef522016-05-05 16:45:40 -06006747 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006748 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006749 break;
John Kessenich91cef522016-05-05 16:45:40 -06006750 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006751 opCode = spv::OpSubgroupAllEqualKHR;
6752 break;
Rex Xu51596642016-09-21 18:56:12 +08006753 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006754 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006755 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006756 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006757 break;
6758 case glslang::EOpReadFirstInvocation:
6759 opCode = spv::OpSubgroupFirstInvocationKHR;
6760 break;
6761 case glslang::EOpBallot:
6762 {
6763 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6764 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6765 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6766 //
6767 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6768 //
6769 spv::Id uintType = builder.makeUintType(32);
6770 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6771 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6772
6773 std::vector<spv::Id> components;
6774 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6775 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6776
6777 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6778 return builder.createUnaryOp(spv::OpBitcast, typeId,
6779 builder.createCompositeConstruct(uvec2Type, components));
6780 }
6781
Rex Xu9d93a232016-05-05 12:30:44 +08006782 case glslang::EOpMinInvocations:
6783 case glslang::EOpMaxInvocations:
6784 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006785 case glslang::EOpMinInvocationsInclusiveScan:
6786 case glslang::EOpMaxInvocationsInclusiveScan:
6787 case glslang::EOpAddInvocationsInclusiveScan:
6788 case glslang::EOpMinInvocationsExclusiveScan:
6789 case glslang::EOpMaxInvocationsExclusiveScan:
6790 case glslang::EOpAddInvocationsExclusiveScan:
6791 if (op == glslang::EOpMinInvocations ||
6792 op == glslang::EOpMinInvocationsInclusiveScan ||
6793 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006794 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006795 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006796 else {
6797 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006798 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006799 else
Rex Xu51596642016-09-21 18:56:12 +08006800 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006801 }
Rex Xu430ef402016-10-14 17:22:23 +08006802 } else if (op == glslang::EOpMaxInvocations ||
6803 op == glslang::EOpMaxInvocationsInclusiveScan ||
6804 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006805 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006806 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006807 else {
6808 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006809 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006810 else
Rex Xu51596642016-09-21 18:56:12 +08006811 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006812 }
6813 } else {
6814 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006815 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006816 else
Rex Xu51596642016-09-21 18:56:12 +08006817 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006818 }
6819
Rex Xu2bbbe062016-08-23 15:41:05 +08006820 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006821 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006822
6823 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006824 case glslang::EOpMinInvocationsNonUniform:
6825 case glslang::EOpMaxInvocationsNonUniform:
6826 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006827 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6828 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6829 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6830 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6831 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6832 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6833 if (op == glslang::EOpMinInvocationsNonUniform ||
6834 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6835 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006836 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006837 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006838 else {
6839 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006840 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006841 else
Rex Xu51596642016-09-21 18:56:12 +08006842 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006843 }
6844 }
Rex Xu430ef402016-10-14 17:22:23 +08006845 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6846 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6847 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006848 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006849 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006850 else {
6851 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006852 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006853 else
Rex Xu51596642016-09-21 18:56:12 +08006854 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006855 }
6856 }
6857 else {
6858 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006859 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006860 else
Rex Xu51596642016-09-21 18:56:12 +08006861 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006862 }
6863
Rex Xu2bbbe062016-08-23 15:41:05 +08006864 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006865 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006866
6867 break;
John Kessenich91cef522016-05-05 16:45:40 -06006868 default:
6869 logger->missingFunctionality("invocation operation");
6870 return spv::NoResult;
6871 }
Rex Xu51596642016-09-21 18:56:12 +08006872
6873 assert(opCode != spv::OpNop);
6874 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006875}
6876
Rex Xu2bbbe062016-08-23 15:41:05 +08006877// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006878spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6879 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006880{
6881 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6882 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006883 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006884 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07006885 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
6886 op == spv::OpGroupSMinNonUniformAMD ||
6887 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
6888 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006889 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6890
6891 // Handle group invocation operations scalar by scalar.
6892 // The result type is the same type as the original type.
6893 // The algorithm is to:
6894 // - break the vector into scalars
6895 // - apply the operation to each scalar
6896 // - make a vector out the scalar results
6897
6898 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006899 int numComponents = builder.getNumComponents(operands[0]);
6900 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006901 std::vector<spv::Id> results;
6902
6903 // do each scalar op
6904 for (int comp = 0; comp < numComponents; ++comp) {
6905 std::vector<unsigned int> indexes;
6906 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006907 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6908 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006909 if (op == spv::OpSubgroupReadInvocationKHR) {
6910 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006911 spv::IdImmediate operand = { true, operands[1] };
6912 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006913 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006914 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6915 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006916 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006917 spv::IdImmediate operand = { true, operands[1] };
6918 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006919 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006920 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6921 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006922 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006923 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006924 spvGroupOperands.push_back(scalar);
6925 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006926
Rex Xub7072052016-09-26 15:53:40 +08006927 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006928 }
6929
6930 // put the pieces together
6931 return builder.createCompositeConstruct(typeId, results);
6932}
Rex Xu2bbbe062016-08-23 15:41:05 +08006933
John Kessenich66011cb2018-03-06 16:12:04 -07006934// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006935spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6936 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006937{
6938 // Add the required capabilities.
6939 switch (op) {
6940 case glslang::EOpSubgroupElect:
6941 builder.addCapability(spv::CapabilityGroupNonUniform);
6942 break;
6943 case glslang::EOpSubgroupAll:
6944 case glslang::EOpSubgroupAny:
6945 case glslang::EOpSubgroupAllEqual:
6946 builder.addCapability(spv::CapabilityGroupNonUniform);
6947 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6948 break;
6949 case glslang::EOpSubgroupBroadcast:
6950 case glslang::EOpSubgroupBroadcastFirst:
6951 case glslang::EOpSubgroupBallot:
6952 case glslang::EOpSubgroupInverseBallot:
6953 case glslang::EOpSubgroupBallotBitExtract:
6954 case glslang::EOpSubgroupBallotBitCount:
6955 case glslang::EOpSubgroupBallotInclusiveBitCount:
6956 case glslang::EOpSubgroupBallotExclusiveBitCount:
6957 case glslang::EOpSubgroupBallotFindLSB:
6958 case glslang::EOpSubgroupBallotFindMSB:
6959 builder.addCapability(spv::CapabilityGroupNonUniform);
6960 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6961 break;
6962 case glslang::EOpSubgroupShuffle:
6963 case glslang::EOpSubgroupShuffleXor:
6964 builder.addCapability(spv::CapabilityGroupNonUniform);
6965 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6966 break;
6967 case glslang::EOpSubgroupShuffleUp:
6968 case glslang::EOpSubgroupShuffleDown:
6969 builder.addCapability(spv::CapabilityGroupNonUniform);
6970 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6971 break;
6972 case glslang::EOpSubgroupAdd:
6973 case glslang::EOpSubgroupMul:
6974 case glslang::EOpSubgroupMin:
6975 case glslang::EOpSubgroupMax:
6976 case glslang::EOpSubgroupAnd:
6977 case glslang::EOpSubgroupOr:
6978 case glslang::EOpSubgroupXor:
6979 case glslang::EOpSubgroupInclusiveAdd:
6980 case glslang::EOpSubgroupInclusiveMul:
6981 case glslang::EOpSubgroupInclusiveMin:
6982 case glslang::EOpSubgroupInclusiveMax:
6983 case glslang::EOpSubgroupInclusiveAnd:
6984 case glslang::EOpSubgroupInclusiveOr:
6985 case glslang::EOpSubgroupInclusiveXor:
6986 case glslang::EOpSubgroupExclusiveAdd:
6987 case glslang::EOpSubgroupExclusiveMul:
6988 case glslang::EOpSubgroupExclusiveMin:
6989 case glslang::EOpSubgroupExclusiveMax:
6990 case glslang::EOpSubgroupExclusiveAnd:
6991 case glslang::EOpSubgroupExclusiveOr:
6992 case glslang::EOpSubgroupExclusiveXor:
6993 builder.addCapability(spv::CapabilityGroupNonUniform);
6994 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6995 break;
6996 case glslang::EOpSubgroupClusteredAdd:
6997 case glslang::EOpSubgroupClusteredMul:
6998 case glslang::EOpSubgroupClusteredMin:
6999 case glslang::EOpSubgroupClusteredMax:
7000 case glslang::EOpSubgroupClusteredAnd:
7001 case glslang::EOpSubgroupClusteredOr:
7002 case glslang::EOpSubgroupClusteredXor:
7003 builder.addCapability(spv::CapabilityGroupNonUniform);
7004 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7005 break;
7006 case glslang::EOpSubgroupQuadBroadcast:
7007 case glslang::EOpSubgroupQuadSwapHorizontal:
7008 case glslang::EOpSubgroupQuadSwapVertical:
7009 case glslang::EOpSubgroupQuadSwapDiagonal:
7010 builder.addCapability(spv::CapabilityGroupNonUniform);
7011 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7012 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007013 case glslang::EOpSubgroupPartitionedAdd:
7014 case glslang::EOpSubgroupPartitionedMul:
7015 case glslang::EOpSubgroupPartitionedMin:
7016 case glslang::EOpSubgroupPartitionedMax:
7017 case glslang::EOpSubgroupPartitionedAnd:
7018 case glslang::EOpSubgroupPartitionedOr:
7019 case glslang::EOpSubgroupPartitionedXor:
7020 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7021 case glslang::EOpSubgroupPartitionedInclusiveMul:
7022 case glslang::EOpSubgroupPartitionedInclusiveMin:
7023 case glslang::EOpSubgroupPartitionedInclusiveMax:
7024 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7025 case glslang::EOpSubgroupPartitionedInclusiveOr:
7026 case glslang::EOpSubgroupPartitionedInclusiveXor:
7027 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7028 case glslang::EOpSubgroupPartitionedExclusiveMul:
7029 case glslang::EOpSubgroupPartitionedExclusiveMin:
7030 case glslang::EOpSubgroupPartitionedExclusiveMax:
7031 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7032 case glslang::EOpSubgroupPartitionedExclusiveOr:
7033 case glslang::EOpSubgroupPartitionedExclusiveXor:
7034 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7035 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7036 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007037 default: assert(0 && "Unhandled subgroup operation!");
7038 }
7039
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007040
7041 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7042 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007043 const bool isBool = typeProxy == glslang::EbtBool;
7044
7045 spv::Op opCode = spv::OpNop;
7046
7047 // Figure out which opcode to use.
7048 switch (op) {
7049 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7050 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7051 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7052 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7053 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7054 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7055 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7056 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7057 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7058 case glslang::EOpSubgroupBallotBitCount:
7059 case glslang::EOpSubgroupBallotInclusiveBitCount:
7060 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7061 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7062 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7063 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7064 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7065 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7066 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7067 case glslang::EOpSubgroupAdd:
7068 case glslang::EOpSubgroupInclusiveAdd:
7069 case glslang::EOpSubgroupExclusiveAdd:
7070 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007071 case glslang::EOpSubgroupPartitionedAdd:
7072 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7073 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007074 if (isFloat) {
7075 opCode = spv::OpGroupNonUniformFAdd;
7076 } else {
7077 opCode = spv::OpGroupNonUniformIAdd;
7078 }
7079 break;
7080 case glslang::EOpSubgroupMul:
7081 case glslang::EOpSubgroupInclusiveMul:
7082 case glslang::EOpSubgroupExclusiveMul:
7083 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007084 case glslang::EOpSubgroupPartitionedMul:
7085 case glslang::EOpSubgroupPartitionedInclusiveMul:
7086 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007087 if (isFloat) {
7088 opCode = spv::OpGroupNonUniformFMul;
7089 } else {
7090 opCode = spv::OpGroupNonUniformIMul;
7091 }
7092 break;
7093 case glslang::EOpSubgroupMin:
7094 case glslang::EOpSubgroupInclusiveMin:
7095 case glslang::EOpSubgroupExclusiveMin:
7096 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007097 case glslang::EOpSubgroupPartitionedMin:
7098 case glslang::EOpSubgroupPartitionedInclusiveMin:
7099 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007100 if (isFloat) {
7101 opCode = spv::OpGroupNonUniformFMin;
7102 } else if (isUnsigned) {
7103 opCode = spv::OpGroupNonUniformUMin;
7104 } else {
7105 opCode = spv::OpGroupNonUniformSMin;
7106 }
7107 break;
7108 case glslang::EOpSubgroupMax:
7109 case glslang::EOpSubgroupInclusiveMax:
7110 case glslang::EOpSubgroupExclusiveMax:
7111 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007112 case glslang::EOpSubgroupPartitionedMax:
7113 case glslang::EOpSubgroupPartitionedInclusiveMax:
7114 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007115 if (isFloat) {
7116 opCode = spv::OpGroupNonUniformFMax;
7117 } else if (isUnsigned) {
7118 opCode = spv::OpGroupNonUniformUMax;
7119 } else {
7120 opCode = spv::OpGroupNonUniformSMax;
7121 }
7122 break;
7123 case glslang::EOpSubgroupAnd:
7124 case glslang::EOpSubgroupInclusiveAnd:
7125 case glslang::EOpSubgroupExclusiveAnd:
7126 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007127 case glslang::EOpSubgroupPartitionedAnd:
7128 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7129 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007130 if (isBool) {
7131 opCode = spv::OpGroupNonUniformLogicalAnd;
7132 } else {
7133 opCode = spv::OpGroupNonUniformBitwiseAnd;
7134 }
7135 break;
7136 case glslang::EOpSubgroupOr:
7137 case glslang::EOpSubgroupInclusiveOr:
7138 case glslang::EOpSubgroupExclusiveOr:
7139 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007140 case glslang::EOpSubgroupPartitionedOr:
7141 case glslang::EOpSubgroupPartitionedInclusiveOr:
7142 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007143 if (isBool) {
7144 opCode = spv::OpGroupNonUniformLogicalOr;
7145 } else {
7146 opCode = spv::OpGroupNonUniformBitwiseOr;
7147 }
7148 break;
7149 case glslang::EOpSubgroupXor:
7150 case glslang::EOpSubgroupInclusiveXor:
7151 case glslang::EOpSubgroupExclusiveXor:
7152 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007153 case glslang::EOpSubgroupPartitionedXor:
7154 case glslang::EOpSubgroupPartitionedInclusiveXor:
7155 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007156 if (isBool) {
7157 opCode = spv::OpGroupNonUniformLogicalXor;
7158 } else {
7159 opCode = spv::OpGroupNonUniformBitwiseXor;
7160 }
7161 break;
7162 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7163 case glslang::EOpSubgroupQuadSwapHorizontal:
7164 case glslang::EOpSubgroupQuadSwapVertical:
7165 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7166 default: assert(0 && "Unhandled subgroup operation!");
7167 }
7168
John Kessenich149afc32018-08-14 13:31:43 -06007169 // get the right Group Operation
7170 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007171 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007172 default:
7173 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007174 case glslang::EOpSubgroupBallotBitCount:
7175 case glslang::EOpSubgroupAdd:
7176 case glslang::EOpSubgroupMul:
7177 case glslang::EOpSubgroupMin:
7178 case glslang::EOpSubgroupMax:
7179 case glslang::EOpSubgroupAnd:
7180 case glslang::EOpSubgroupOr:
7181 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007182 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007183 break;
7184 case glslang::EOpSubgroupBallotInclusiveBitCount:
7185 case glslang::EOpSubgroupInclusiveAdd:
7186 case glslang::EOpSubgroupInclusiveMul:
7187 case glslang::EOpSubgroupInclusiveMin:
7188 case glslang::EOpSubgroupInclusiveMax:
7189 case glslang::EOpSubgroupInclusiveAnd:
7190 case glslang::EOpSubgroupInclusiveOr:
7191 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007192 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007193 break;
7194 case glslang::EOpSubgroupBallotExclusiveBitCount:
7195 case glslang::EOpSubgroupExclusiveAdd:
7196 case glslang::EOpSubgroupExclusiveMul:
7197 case glslang::EOpSubgroupExclusiveMin:
7198 case glslang::EOpSubgroupExclusiveMax:
7199 case glslang::EOpSubgroupExclusiveAnd:
7200 case glslang::EOpSubgroupExclusiveOr:
7201 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007202 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007203 break;
7204 case glslang::EOpSubgroupClusteredAdd:
7205 case glslang::EOpSubgroupClusteredMul:
7206 case glslang::EOpSubgroupClusteredMin:
7207 case glslang::EOpSubgroupClusteredMax:
7208 case glslang::EOpSubgroupClusteredAnd:
7209 case glslang::EOpSubgroupClusteredOr:
7210 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007211 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007212 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007213 case glslang::EOpSubgroupPartitionedAdd:
7214 case glslang::EOpSubgroupPartitionedMul:
7215 case glslang::EOpSubgroupPartitionedMin:
7216 case glslang::EOpSubgroupPartitionedMax:
7217 case glslang::EOpSubgroupPartitionedAnd:
7218 case glslang::EOpSubgroupPartitionedOr:
7219 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007220 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007221 break;
7222 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7223 case glslang::EOpSubgroupPartitionedInclusiveMul:
7224 case glslang::EOpSubgroupPartitionedInclusiveMin:
7225 case glslang::EOpSubgroupPartitionedInclusiveMax:
7226 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7227 case glslang::EOpSubgroupPartitionedInclusiveOr:
7228 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007229 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007230 break;
7231 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7232 case glslang::EOpSubgroupPartitionedExclusiveMul:
7233 case glslang::EOpSubgroupPartitionedExclusiveMin:
7234 case glslang::EOpSubgroupPartitionedExclusiveMax:
7235 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7236 case glslang::EOpSubgroupPartitionedExclusiveOr:
7237 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007238 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007239 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007240 }
7241
John Kessenich149afc32018-08-14 13:31:43 -06007242 // build the instruction
7243 std::vector<spv::IdImmediate> spvGroupOperands;
7244
7245 // Every operation begins with the Execution Scope operand.
7246 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7247 spvGroupOperands.push_back(executionScope);
7248
7249 // Next, for all operations that use a Group Operation, push that as an operand.
7250 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007251 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007252 spvGroupOperands.push_back(groupOperand);
7253 }
7254
John Kessenich66011cb2018-03-06 16:12:04 -07007255 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007256 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7257 spv::IdImmediate operand = { true, *opIt };
7258 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007259 }
7260
7261 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007262 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007263 switch (op) {
7264 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007265 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7266 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7267 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7268 }
7269 if (directionId != spv::NoResult) {
7270 spv::IdImmediate direction = { true, directionId };
7271 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007272 }
7273
7274 return builder.createOp(opCode, typeId, spvGroupOperands);
7275}
7276
John Kessenich8985fc92020-03-03 10:25:07 -07007277spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7278 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007279{
John Kessenich66011cb2018-03-06 16:12:04 -07007280 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7281 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007282
John Kessenich140f3df2015-06-26 16:58:36 -06007283 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007284 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007285 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007286 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007287 spv::Id typeId0 = 0;
7288 if (consumedOperands > 0)
7289 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007290 spv::Id typeId1 = 0;
7291 if (consumedOperands > 1)
7292 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007293 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007294
7295 switch (op) {
7296 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007297 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007298 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007299 else if (isUnsigned)
7300 libCall = spv::GLSLstd450UMin;
7301 else
7302 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007303 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007304 break;
7305 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007306 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007307 break;
7308 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007309 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007310 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007311 else if (isUnsigned)
7312 libCall = spv::GLSLstd450UMax;
7313 else
7314 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007315 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007316 break;
7317 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007318 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007319 break;
7320 case glslang::EOpDot:
7321 opCode = spv::OpDot;
7322 break;
7323 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007324 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007325 break;
7326
7327 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007328 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007329 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007330 else if (isUnsigned)
7331 libCall = spv::GLSLstd450UClamp;
7332 else
7333 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007334 builder.promoteScalar(precision, operands.front(), operands[1]);
7335 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007336 break;
7337 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007338 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7339 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007340 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007341 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007342 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007343 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007344 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007345 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007346 break;
7347 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007348 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007349 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007350 break;
7351 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007352 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007353 builder.promoteScalar(precision, operands[0], operands[2]);
7354 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007355 break;
7356
7357 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007358 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007359 break;
7360 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007361 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007362 break;
7363 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007364 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007365 break;
7366 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007367 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007368 break;
7369 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007370 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007371 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007372 case glslang::EOpBarrier:
7373 {
7374 // This is for the extended controlBarrier function, with four operands.
7375 // The unextended barrier() goes through createNoArgOperation.
7376 assert(operands.size() == 4);
7377 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7378 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7379 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007380 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7381 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007382 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7383 spv::MemorySemanticsMakeVisibleKHRMask |
7384 spv::MemorySemanticsOutputMemoryKHRMask |
7385 spv::MemorySemanticsVolatileMask)) {
7386 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7387 }
John Kessenich8985fc92020-03-03 10:25:07 -07007388 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7389 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007390 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7391 }
7392 return 0;
7393 }
7394 break;
7395 case glslang::EOpMemoryBarrier:
7396 {
7397 // This is for the extended memoryBarrier function, with three operands.
7398 // The unextended memoryBarrier() goes through createNoArgOperation.
7399 assert(operands.size() == 3);
7400 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7401 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7402 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7403 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7404 spv::MemorySemanticsMakeVisibleKHRMask |
7405 spv::MemorySemanticsOutputMemoryKHRMask |
7406 spv::MemorySemanticsVolatileMask)) {
7407 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7408 }
7409 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7410 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7411 }
7412 return 0;
7413 }
7414 break;
7415
John Kessenicha28f7a72019-08-06 07:00:58 -06007416#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007417 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007418 if (typeProxy == glslang::EbtFloat16)
7419 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007420 libCall = spv::GLSLstd450InterpolateAtSample;
7421 break;
7422 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007423 if (typeProxy == glslang::EbtFloat16)
7424 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007425 libCall = spv::GLSLstd450InterpolateAtOffset;
7426 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007427 case glslang::EOpAddCarry:
7428 opCode = spv::OpIAddCarry;
7429 typeId = builder.makeStructResultType(typeId0, typeId0);
7430 consumedOperands = 2;
7431 break;
7432 case glslang::EOpSubBorrow:
7433 opCode = spv::OpISubBorrow;
7434 typeId = builder.makeStructResultType(typeId0, typeId0);
7435 consumedOperands = 2;
7436 break;
7437 case glslang::EOpUMulExtended:
7438 opCode = spv::OpUMulExtended;
7439 typeId = builder.makeStructResultType(typeId0, typeId0);
7440 consumedOperands = 2;
7441 break;
7442 case glslang::EOpIMulExtended:
7443 opCode = spv::OpSMulExtended;
7444 typeId = builder.makeStructResultType(typeId0, typeId0);
7445 consumedOperands = 2;
7446 break;
7447 case glslang::EOpBitfieldExtract:
7448 if (isUnsigned)
7449 opCode = spv::OpBitFieldUExtract;
7450 else
7451 opCode = spv::OpBitFieldSExtract;
7452 break;
7453 case glslang::EOpBitfieldInsert:
7454 opCode = spv::OpBitFieldInsert;
7455 break;
7456
7457 case glslang::EOpFma:
7458 libCall = spv::GLSLstd450Fma;
7459 break;
7460 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007461 {
7462 libCall = spv::GLSLstd450FrexpStruct;
7463 assert(builder.isPointerType(typeId1));
7464 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007465 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007466 if (width == 16)
7467 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7468 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007469 if (builder.getNumComponents(operands[0]) == 1)
7470 frexpIntType = builder.makeIntegerType(width, true);
7471 else
John Kessenich8985fc92020-03-03 10:25:07 -07007472 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7473 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007474 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7475 consumedOperands = 1;
7476 }
John Kessenich55e7d112015-11-15 21:33:39 -07007477 break;
7478 case glslang::EOpLdexp:
7479 libCall = spv::GLSLstd450Ldexp;
7480 break;
7481
Rex Xu574ab042016-04-14 16:53:07 +08007482 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007483 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007484
John Kessenich66011cb2018-03-06 16:12:04 -07007485 case glslang::EOpSubgroupBroadcast:
7486 case glslang::EOpSubgroupBallotBitExtract:
7487 case glslang::EOpSubgroupShuffle:
7488 case glslang::EOpSubgroupShuffleXor:
7489 case glslang::EOpSubgroupShuffleUp:
7490 case glslang::EOpSubgroupShuffleDown:
7491 case glslang::EOpSubgroupClusteredAdd:
7492 case glslang::EOpSubgroupClusteredMul:
7493 case glslang::EOpSubgroupClusteredMin:
7494 case glslang::EOpSubgroupClusteredMax:
7495 case glslang::EOpSubgroupClusteredAnd:
7496 case glslang::EOpSubgroupClusteredOr:
7497 case glslang::EOpSubgroupClusteredXor:
7498 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007499 case glslang::EOpSubgroupPartitionedAdd:
7500 case glslang::EOpSubgroupPartitionedMul:
7501 case glslang::EOpSubgroupPartitionedMin:
7502 case glslang::EOpSubgroupPartitionedMax:
7503 case glslang::EOpSubgroupPartitionedAnd:
7504 case glslang::EOpSubgroupPartitionedOr:
7505 case glslang::EOpSubgroupPartitionedXor:
7506 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7507 case glslang::EOpSubgroupPartitionedInclusiveMul:
7508 case glslang::EOpSubgroupPartitionedInclusiveMin:
7509 case glslang::EOpSubgroupPartitionedInclusiveMax:
7510 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7511 case glslang::EOpSubgroupPartitionedInclusiveOr:
7512 case glslang::EOpSubgroupPartitionedInclusiveXor:
7513 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7514 case glslang::EOpSubgroupPartitionedExclusiveMul:
7515 case glslang::EOpSubgroupPartitionedExclusiveMin:
7516 case glslang::EOpSubgroupPartitionedExclusiveMax:
7517 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7518 case glslang::EOpSubgroupPartitionedExclusiveOr:
7519 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007520 return createSubgroupOperation(op, typeId, operands, typeProxy);
7521
Rex Xu9d93a232016-05-05 12:30:44 +08007522 case glslang::EOpSwizzleInvocations:
7523 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7524 libCall = spv::SwizzleInvocationsAMD;
7525 break;
7526 case glslang::EOpSwizzleInvocationsMasked:
7527 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7528 libCall = spv::SwizzleInvocationsMaskedAMD;
7529 break;
7530 case glslang::EOpWriteInvocation:
7531 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7532 libCall = spv::WriteInvocationAMD;
7533 break;
7534
7535 case glslang::EOpMin3:
7536 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7537 if (isFloat)
7538 libCall = spv::FMin3AMD;
7539 else {
7540 if (isUnsigned)
7541 libCall = spv::UMin3AMD;
7542 else
7543 libCall = spv::SMin3AMD;
7544 }
7545 break;
7546 case glslang::EOpMax3:
7547 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7548 if (isFloat)
7549 libCall = spv::FMax3AMD;
7550 else {
7551 if (isUnsigned)
7552 libCall = spv::UMax3AMD;
7553 else
7554 libCall = spv::SMax3AMD;
7555 }
7556 break;
7557 case glslang::EOpMid3:
7558 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7559 if (isFloat)
7560 libCall = spv::FMid3AMD;
7561 else {
7562 if (isUnsigned)
7563 libCall = spv::UMid3AMD;
7564 else
7565 libCall = spv::SMid3AMD;
7566 }
7567 break;
7568
7569 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007570 if (typeProxy == glslang::EbtFloat16)
7571 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007572 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7573 libCall = spv::InterpolateAtVertexAMD;
7574 break;
Chao Chen3c366992018-09-19 11:41:59 -07007575
Chao Chenb50c02e2018-09-19 11:42:24 -07007576 case glslang::EOpReportIntersectionNV:
7577 {
7578 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007579 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007580 }
7581 break;
7582 case glslang::EOpTraceNV:
7583 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007584 builder.createNoResultOp(spv::OpTraceNV, operands);
7585 return 0;
7586 }
7587 break;
7588 case glslang::EOpExecuteCallableNV:
7589 {
7590 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007591 return 0;
7592 }
7593 break;
Chao Chen3c366992018-09-19 11:41:59 -07007594 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7595 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7596 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007597 case glslang::EOpCooperativeMatrixMulAdd:
7598 opCode = spv::OpCooperativeMatrixMulAddNV;
7599 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007600#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007601 default:
7602 return 0;
7603 }
7604
7605 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007606 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007607 // Use an extended instruction from the standard library.
7608 // Construct the call arguments, without modifying the original operands vector.
7609 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7610 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007611 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007612 } else if (opCode == spv::OpDot && !isFloat) {
7613 // int dot(int, int)
7614 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7615 const int componentCount = builder.getNumComponents(operands[0]);
7616 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7617 builder.setPrecision(mulOp, precision);
7618 id = builder.createCompositeExtract(mulOp, typeId, 0);
7619 for (int i = 1; i < componentCount; ++i) {
7620 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007621 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007622 }
John Kessenich2359bd02015-12-06 19:29:11 -07007623 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007624 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007625 case 0:
7626 // should all be handled by visitAggregate and createNoArgOperation
7627 assert(0);
7628 return 0;
7629 case 1:
7630 // should all be handled by createUnaryOperation
7631 assert(0);
7632 return 0;
7633 case 2:
7634 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7635 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007636 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007637 // anything 3 or over doesn't have l-value operands, so all should be consumed
7638 assert(consumedOperands == operands.size());
7639 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007640 break;
7641 }
7642 }
7643
John Kessenichb9197c82019-08-11 07:41:45 -06007644#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007645 // Decode the return types that were structures
7646 switch (op) {
7647 case glslang::EOpAddCarry:
7648 case glslang::EOpSubBorrow:
7649 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7650 id = builder.createCompositeExtract(id, typeId0, 0);
7651 break;
7652 case glslang::EOpUMulExtended:
7653 case glslang::EOpIMulExtended:
7654 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7655 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7656 break;
7657 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007658 {
7659 assert(operands.size() == 2);
7660 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7661 // "exp" is floating-point type (from HLSL intrinsic)
7662 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7663 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7664 builder.createStore(member1, operands[1]);
7665 } else
7666 // "exp" is integer type (from GLSL built-in function)
7667 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7668 id = builder.createCompositeExtract(id, typeId0, 0);
7669 }
John Kessenich55e7d112015-11-15 21:33:39 -07007670 break;
7671 default:
7672 break;
7673 }
John Kessenichb9197c82019-08-11 07:41:45 -06007674#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007675
John Kessenich32cfd492016-02-02 12:37:46 -07007676 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007677}
7678
Rex Xu9d93a232016-05-05 12:30:44 +08007679// Intrinsics with no arguments (or no return value, and no precision).
7680spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007681{
Jeff Bolz36831c92018-09-05 10:11:41 -05007682 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007683 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7684 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007685
7686 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007687 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007688 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007689 if (glslangIntermediate->usingVulkanMemoryModel()) {
7690 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7691 spv::MemorySemanticsOutputMemoryKHRMask |
7692 spv::MemorySemanticsAcquireReleaseMask);
7693 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7694 } else {
7695 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7696 }
John Kessenich82979362017-12-11 04:02:24 -07007697 } else {
7698 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7699 spv::MemorySemanticsWorkgroupMemoryMask |
7700 spv::MemorySemanticsAcquireReleaseMask);
7701 }
John Kessenich140f3df2015-06-26 16:58:36 -06007702 return 0;
7703 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007704 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7705 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007706 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007707 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007708 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7709 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007710 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007711 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007712 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7713 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007714 return 0;
7715 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007716 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7717 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007718 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007719#ifndef GLSLANG_WEB
7720 case glslang::EOpMemoryBarrierAtomicCounter:
7721 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7722 spv::MemorySemanticsAcquireReleaseMask);
7723 return 0;
7724 case glslang::EOpMemoryBarrierImage:
7725 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7726 spv::MemorySemanticsAcquireReleaseMask);
7727 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007728 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007729 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007730 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007731 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007732 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007733 case glslang::EOpDeviceMemoryBarrier:
7734 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7735 spv::MemorySemanticsImageMemoryMask |
7736 spv::MemorySemanticsAcquireReleaseMask);
7737 return 0;
7738 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7739 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7740 spv::MemorySemanticsImageMemoryMask |
7741 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007742 return 0;
7743 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007744 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7745 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007746 return 0;
7747 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007748 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7749 spv::MemorySemanticsWorkgroupMemoryMask |
7750 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007751 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007752 case glslang::EOpSubgroupBarrier:
7753 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7754 spv::MemorySemanticsAcquireReleaseMask);
7755 return spv::NoResult;
7756 case glslang::EOpSubgroupMemoryBarrier:
7757 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7758 spv::MemorySemanticsAcquireReleaseMask);
7759 return spv::NoResult;
7760 case glslang::EOpSubgroupMemoryBarrierBuffer:
7761 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7762 spv::MemorySemanticsAcquireReleaseMask);
7763 return spv::NoResult;
7764 case glslang::EOpSubgroupMemoryBarrierImage:
7765 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7766 spv::MemorySemanticsAcquireReleaseMask);
7767 return spv::NoResult;
7768 case glslang::EOpSubgroupMemoryBarrierShared:
7769 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7770 spv::MemorySemanticsAcquireReleaseMask);
7771 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007772
7773 case glslang::EOpEmitVertex:
7774 builder.createNoResultOp(spv::OpEmitVertex);
7775 return 0;
7776 case glslang::EOpEndPrimitive:
7777 builder.createNoResultOp(spv::OpEndPrimitive);
7778 return 0;
7779
John Kessenich66011cb2018-03-06 16:12:04 -07007780 case glslang::EOpSubgroupElect: {
7781 std::vector<spv::Id> operands;
7782 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7783 }
Rex Xu9d93a232016-05-05 12:30:44 +08007784 case glslang::EOpTime:
7785 {
7786 std::vector<spv::Id> args; // Dummy arguments
7787 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7788 return builder.setPrecision(id, precision);
7789 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007790 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007791 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007792 return 0;
7793 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007794 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007795 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007796
7797 case glslang::EOpBeginInvocationInterlock:
7798 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7799 return 0;
7800 case glslang::EOpEndInvocationInterlock:
7801 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7802 return 0;
7803
Jeff Bolzba6170b2019-07-01 09:23:23 -05007804 case glslang::EOpIsHelperInvocation:
7805 {
7806 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007807 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7808 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7809 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007810 }
7811
amhagan91fb0092019-07-10 21:14:38 -04007812 case glslang::EOpReadClockSubgroupKHR: {
7813 std::vector<spv::Id> args;
7814 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7815 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7816 builder.addCapability(spv::CapabilityShaderClockKHR);
7817 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7818 }
7819
7820 case glslang::EOpReadClockDeviceKHR: {
7821 std::vector<spv::Id> args;
7822 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7823 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7824 builder.addCapability(spv::CapabilityShaderClockKHR);
7825 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7826 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007827#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007828 default:
John Kessenich155d3512019-08-08 23:29:20 -06007829 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007830 }
John Kessenich155d3512019-08-08 23:29:20 -06007831
7832 logger->missingFunctionality("unknown operation with no arguments");
7833
7834 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007835}
7836
7837spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7838{
John Kessenich2f273362015-07-18 22:34:27 -06007839 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007840 spv::Id id;
7841 if (symbolValues.end() != iter) {
7842 id = iter->second;
7843 return id;
7844 }
7845
7846 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007847 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7848 auto forcedType = getForcedType(builtIn, symbol->getType());
7849 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007850 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007851 if (forcedType.second != spv::NoType)
7852 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007853
Rex Xuc884b4a2016-06-29 15:03:44 +08007854 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007855 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7856 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7857 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007858#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007859 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007860 if (symbol->getQualifier().hasComponent())
7861 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7862 if (symbol->getQualifier().hasIndex())
7863 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007864#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007865 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007866 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007867 // atomic counters use this:
7868 if (symbol->getQualifier().hasOffset())
7869 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007870 }
7871
scygan2c864272016-05-18 18:09:17 +02007872 if (symbol->getQualifier().hasLocation())
7873 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007874 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007875 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007876 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007877 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007878 }
John Kessenich140f3df2015-06-26 16:58:36 -06007879 if (symbol->getQualifier().hasSet())
7880 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007881 else if (IsDescriptorResource(symbol->getType())) {
7882 // default to 0
7883 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7884 }
John Kessenich140f3df2015-06-26 16:58:36 -06007885 if (symbol->getQualifier().hasBinding())
7886 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007887 else if (IsDescriptorResource(symbol->getType())) {
7888 // default to 0
7889 builder.addDecoration(id, spv::DecorationBinding, 0);
7890 }
John Kessenich6c292d32016-02-15 20:58:50 -07007891 if (symbol->getQualifier().hasAttachment())
7892 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007893 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007894 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007895 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007896 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007897 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7898 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7899 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7900 }
7901 if (symbol->getQualifier().hasXfbOffset())
7902 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007903 }
7904
John Kessenichb9197c82019-08-11 07:41:45 -06007905 // add built-in variable decoration
7906 if (builtIn != spv::BuiltInMax) {
7907 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7908 }
7909
7910#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007911 if (symbol->getType().isImage()) {
7912 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07007913 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
7914 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007915 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007916 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007917 }
7918
John Kessenich5611c6d2018-04-05 11:25:02 -06007919 // nonuniform
7920 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7921
chaoc0ad6a4e2016-12-19 16:29:34 -08007922 if (builtIn == spv::BuiltInSampleMask) {
7923 spv::Decoration decoration;
7924 // GL_NV_sample_mask_override_coverage extension
7925 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007926 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007927 else
7928 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007929 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007930 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007931 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007932 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7933 }
7934 }
chaoc771d89f2017-01-13 01:10:53 -08007935 else if (builtIn == spv::BuiltInLayer) {
7936 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007937 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007938 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007939 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7940 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7941 }
John Kessenichb41bff62017-08-11 13:07:17 -06007942 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007943 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7944 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007945 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7946 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7947 }
7948 }
7949
chaoc6e5acae2016-12-20 13:28:52 -08007950 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007951 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007952 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007953 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7954 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007955 if (symbol->getQualifier().pervertexNV) {
7956 builder.addDecoration(id, spv::DecorationPerVertexNV);
7957 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7958 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7959 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007960
John Kessenich5d610ee2018-03-07 18:05:55 -07007961 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7962 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7963 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7964 symbol->getType().getQualifier().semanticName);
7965 }
7966
John Kessenich7015bd62019-08-01 03:28:08 -06007967 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07007968 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
7969 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007970 }
John Kessenichb9197c82019-08-11 07:41:45 -06007971#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007972
John Kessenich140f3df2015-06-26 16:58:36 -06007973 return id;
7974}
7975
John Kessenicha28f7a72019-08-06 07:00:58 -06007976#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007977// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7978void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7979{
7980 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007981 if (qualifier.perPrimitiveNV) {
7982 // Need to add capability/extension for fragment shader.
7983 // Mesh shader already adds this by default.
7984 if (glslangIntermediate->getStage() == EShLangFragment) {
7985 builder.addCapability(spv::CapabilityMeshShadingNV);
7986 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7987 }
Chao Chen3c366992018-09-19 11:41:59 -07007988 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007989 }
Chao Chen3c366992018-09-19 11:41:59 -07007990 if (qualifier.perViewNV)
7991 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7992 if (qualifier.perTaskNV)
7993 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7994 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007995 if (qualifier.perPrimitiveNV) {
7996 // Need to add capability/extension for fragment shader.
7997 // Mesh shader already adds this by default.
7998 if (glslangIntermediate->getStage() == EShLangFragment) {
7999 builder.addCapability(spv::CapabilityMeshShadingNV);
8000 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8001 }
Chao Chen3c366992018-09-19 11:41:59 -07008002 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008003 }
Chao Chen3c366992018-09-19 11:41:59 -07008004 if (qualifier.perViewNV)
8005 builder.addDecoration(id, spv::DecorationPerViewNV);
8006 if (qualifier.perTaskNV)
8007 builder.addDecoration(id, spv::DecorationPerTaskNV);
8008 }
8009}
8010#endif
8011
John Kessenich55e7d112015-11-15 21:33:39 -07008012// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008013// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008014//
8015// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8016//
8017// Recursively walk the nodes. The nodes form a tree whose leaves are
8018// regular constants, which themselves are trees that createSpvConstant()
8019// recursively walks. So, this function walks the "top" of the tree:
8020// - emit specialization constant-building instructions for specConstant
8021// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008022spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008023{
John Kessenich7cc0e282016-03-20 00:46:02 -06008024 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008025
qining4f4bb812016-04-03 23:55:17 -04008026 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008027 if (! node.getQualifier().specConstant) {
8028 // hand off to the non-spec-constant path
8029 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8030 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008031 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8032 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8033 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008034 }
8035
8036 // We now know we have a specialization constant to build
8037
John Kessenichd94c0032016-05-30 19:29:40 -06008038 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008039 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8040 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8041 std::vector<spv::Id> dimConstId;
8042 for (int dim = 0; dim < 3; ++dim) {
8043 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8044 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008045 if (specConst) {
8046 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8047 glslangIntermediate->getLocalSizeSpecId(dim));
8048 }
qining4f4bb812016-04-03 23:55:17 -04008049 }
8050 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8051 }
8052
8053 // An AST node labelled as specialization constant should be a symbol node.
8054 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8055 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008056 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008057 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008058 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8059 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8060 // will set the builder into spec constant op instruction generating mode.
8061 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008062 result = accessChainLoad(sub_tree->getType());
8063 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008064 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008065 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008066 } else {
8067 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008068 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008069 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008070 builder.addName(result, sn->getName().c_str());
8071 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008072 }
qining4f4bb812016-04-03 23:55:17 -04008073
8074 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8075 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008076 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008077 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008078}
8079
John Kessenich140f3df2015-06-26 16:58:36 -06008080// Use 'consts' as the flattened glslang source of scalar constants to recursively
8081// build the aggregate SPIR-V constant.
8082//
8083// If there are not enough elements present in 'consts', 0 will be substituted;
8084// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8085//
John Kessenich8985fc92020-03-03 10:25:07 -07008086spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8087 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008088{
8089 // vector of constants for SPIR-V
8090 std::vector<spv::Id> spvConsts;
8091
8092 // Type is used for struct and array constants
8093 spv::Id typeId = convertGlslangToSpvType(glslangType);
8094
8095 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008096 glslang::TType elementType(glslangType, 0);
8097 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008098 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008099 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008100 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008101 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008102 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008103 } else if (glslangType.isCoopMat()) {
8104 glslang::TType componentType(glslangType.getBasicType());
8105 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008106 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008107 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8108 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008109 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008110 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008111 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8112 bool zero = nextConst >= consts.size();
8113 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008114 case glslang::EbtInt:
8115 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8116 break;
8117 case glslang::EbtUint:
8118 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8119 break;
8120 case glslang::EbtFloat:
8121 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8122 break;
8123 case glslang::EbtBool:
8124 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8125 break;
8126#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008127 case glslang::EbtInt8:
8128 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8129 break;
8130 case glslang::EbtUint8:
8131 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8132 break;
8133 case glslang::EbtInt16:
8134 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8135 break;
8136 case glslang::EbtUint16:
8137 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8138 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008139 case glslang::EbtInt64:
8140 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8141 break;
8142 case glslang::EbtUint64:
8143 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8144 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008145 case glslang::EbtDouble:
8146 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8147 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008148 case glslang::EbtFloat16:
8149 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8150 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008151#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008152 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008153 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008154 break;
8155 }
8156 ++nextConst;
8157 }
8158 } else {
8159 // we have a non-aggregate (scalar) constant
8160 bool zero = nextConst >= consts.size();
8161 spv::Id scalar = 0;
8162 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008163 case glslang::EbtInt:
8164 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8165 break;
8166 case glslang::EbtUint:
8167 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8168 break;
8169 case glslang::EbtFloat:
8170 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8171 break;
8172 case glslang::EbtBool:
8173 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8174 break;
8175#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008176 case glslang::EbtInt8:
8177 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8178 break;
8179 case glslang::EbtUint8:
8180 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8181 break;
8182 case glslang::EbtInt16:
8183 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8184 break;
8185 case glslang::EbtUint16:
8186 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8187 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008188 case glslang::EbtInt64:
8189 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8190 break;
8191 case glslang::EbtUint64:
8192 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8193 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008194 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008195 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008196 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008197 case glslang::EbtFloat16:
8198 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8199 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008200 case glslang::EbtReference:
8201 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8202 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8203 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008204#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008205 case glslang::EbtString:
8206 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8207 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008208 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008209 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008210 break;
8211 }
8212 ++nextConst;
8213 return scalar;
8214 }
8215
8216 return builder.makeCompositeConstant(typeId, spvConsts);
8217}
8218
John Kessenich7c1aa102015-10-15 13:29:11 -06008219// Return true if the node is a constant or symbol whose reading has no
8220// non-trivial observable cost or effect.
8221bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8222{
8223 // don't know what this is
8224 if (node == nullptr)
8225 return false;
8226
8227 // a constant is safe
8228 if (node->getAsConstantUnion() != nullptr)
8229 return true;
8230
8231 // not a symbol means non-trivial
8232 if (node->getAsSymbolNode() == nullptr)
8233 return false;
8234
8235 // a symbol, depends on what's being read
8236 switch (node->getType().getQualifier().storage) {
8237 case glslang::EvqTemporary:
8238 case glslang::EvqGlobal:
8239 case glslang::EvqIn:
8240 case glslang::EvqInOut:
8241 case glslang::EvqConst:
8242 case glslang::EvqConstReadOnly:
8243 case glslang::EvqUniform:
8244 return true;
8245 default:
8246 return false;
8247 }
qining25262b32016-05-06 17:25:16 -04008248}
John Kessenich7c1aa102015-10-15 13:29:11 -06008249
8250// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008251// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008252// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008253// Return true if trivial.
8254bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8255{
8256 if (node == nullptr)
8257 return false;
8258
John Kessenich84cc15f2017-05-24 16:44:47 -06008259 // count non scalars as trivial, as well as anything coming from HLSL
8260 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008261 return true;
8262
John Kessenich7c1aa102015-10-15 13:29:11 -06008263 // symbols and constants are trivial
8264 if (isTrivialLeaf(node))
8265 return true;
8266
8267 // otherwise, it needs to be a simple operation or one or two leaf nodes
8268
8269 // not a simple operation
8270 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8271 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8272 if (binaryNode == nullptr && unaryNode == nullptr)
8273 return false;
8274
8275 // not on leaf nodes
8276 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8277 return false;
8278
8279 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8280 return false;
8281 }
8282
8283 switch (node->getAsOperator()->getOp()) {
8284 case glslang::EOpLogicalNot:
8285 case glslang::EOpConvIntToBool:
8286 case glslang::EOpConvUintToBool:
8287 case glslang::EOpConvFloatToBool:
8288 case glslang::EOpConvDoubleToBool:
8289 case glslang::EOpEqual:
8290 case glslang::EOpNotEqual:
8291 case glslang::EOpLessThan:
8292 case glslang::EOpGreaterThan:
8293 case glslang::EOpLessThanEqual:
8294 case glslang::EOpGreaterThanEqual:
8295 case glslang::EOpIndexDirect:
8296 case glslang::EOpIndexDirectStruct:
8297 case glslang::EOpLogicalXor:
8298 case glslang::EOpAny:
8299 case glslang::EOpAll:
8300 return true;
8301 default:
8302 return false;
8303 }
8304}
8305
8306// Emit short-circuiting code, where 'right' is never evaluated unless
8307// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008308spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8309 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008310{
8311 spv::Id boolTypeId = builder.makeBoolType();
8312
8313 // emit left operand
8314 builder.clearAccessChain();
8315 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008316 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008317
8318 // Operands to accumulate OpPhi operands
8319 std::vector<spv::Id> phiOperands;
8320 // accumulate left operand's phi information
8321 phiOperands.push_back(leftId);
8322 phiOperands.push_back(builder.getBuildPoint()->getId());
8323
8324 // Make the two kinds of operation symmetric with a "!"
8325 // || => emit "if (! left) result = right"
8326 // && => emit "if ( left) result = right"
8327 //
8328 // TODO: this runtime "not" for || could be avoided by adding functionality
8329 // to 'builder' to have an "else" without an "then"
8330 if (op == glslang::EOpLogicalOr)
8331 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8332
8333 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008334 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008335
8336 // emit right operand as the "then" part of the "if"
8337 builder.clearAccessChain();
8338 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008339 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008340
8341 // accumulate left operand's phi information
8342 phiOperands.push_back(rightId);
8343 phiOperands.push_back(builder.getBuildPoint()->getId());
8344
8345 // finish the "if"
8346 ifBuilder.makeEndIf();
8347
8348 // phi together the two results
8349 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8350}
8351
John Kessenicha28f7a72019-08-06 07:00:58 -06008352#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008353// Return type Id of the imported set of extended instructions corresponds to the name.
8354// Import this set if it has not been imported yet.
8355spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8356{
8357 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8358 return extBuiltinMap[name];
8359 else {
Rex Xu51596642016-09-21 18:56:12 +08008360 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008361 spv::Id extBuiltins = builder.import(name);
8362 extBuiltinMap[name] = extBuiltins;
8363 return extBuiltins;
8364 }
8365}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008366#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008367
John Kessenich140f3df2015-06-26 16:58:36 -06008368}; // end anonymous namespace
8369
8370namespace glslang {
8371
John Kessenich68d78fd2015-07-12 19:28:10 -06008372void GetSpirvVersion(std::string& version)
8373{
John Kessenich9e55f632015-07-15 10:03:39 -06008374 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008375 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008376 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008377 version = buf;
8378}
8379
John Kessenicha372a3e2017-11-02 22:32:14 -06008380// For low-order part of the generator's magic number. Bump up
8381// when there is a change in the style (e.g., if SSA form changes,
8382// or a different instruction sequence to do something gets used).
8383int GetSpirvGeneratorVersion()
8384{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008385 // return 1; // start
8386 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008387 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008388 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008389 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008390 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8391 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008392 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8393 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008394}
8395
John Kessenich140f3df2015-06-26 16:58:36 -06008396// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008397void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008398{
8399 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008400 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008401 if (out.fail())
8402 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008403 for (int i = 0; i < (int)spirv.size(); ++i) {
8404 unsigned int word = spirv[i];
8405 out.write((const char*)&word, 4);
8406 }
8407 out.close();
8408}
8409
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008410// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008411void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008412{
John Kessenich155d3512019-08-08 23:29:20 -06008413#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008414 std::ofstream out;
8415 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008416 if (out.fail())
8417 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008418 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008419 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008420 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008421 if (varName != nullptr) {
8422 out << "\t #pragma once" << std::endl;
8423 out << "const uint32_t " << varName << "[] = {" << std::endl;
8424 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008425 const int WORDS_PER_LINE = 8;
8426 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8427 out << "\t";
8428 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8429 const unsigned int word = spirv[i + j];
8430 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8431 if (i + j + 1 < (int)spirv.size()) {
8432 out << ",";
8433 }
8434 }
8435 out << std::endl;
8436 }
Flavio15017db2017-02-15 14:29:33 -08008437 if (varName != nullptr) {
8438 out << "};";
8439 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008440 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008441#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008442}
8443
John Kessenich140f3df2015-06-26 16:58:36 -06008444//
8445// Set up the glslang traversal
8446//
John Kessenich4e11b612018-08-30 16:56:59 -06008447void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008448{
Lei Zhang17535f72016-05-04 15:55:59 -04008449 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008450 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008451}
8452
John Kessenich4e11b612018-08-30 16:56:59 -06008453void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008454 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008455{
John Kessenich140f3df2015-06-26 16:58:36 -06008456 TIntermNode* root = intermediate.getTreeRoot();
8457
8458 if (root == 0)
8459 return;
8460
John Kessenich4e11b612018-08-30 16:56:59 -06008461 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008462 if (options == nullptr)
8463 options = &defaultOptions;
8464
John Kessenich4e11b612018-08-30 16:56:59 -06008465 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008466
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008467 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008468 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008469 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008470 it.dumpSpv(spirv);
8471
GregFfb03a552018-03-29 11:49:14 -06008472#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008473 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8474 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008475 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8476 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008477 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008478 prelegalization = false;
8479 }
John Kessenich717c80a2018-08-23 15:17:10 -06008480
John Kessenich4e11b612018-08-30 16:56:59 -06008481 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008482 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008483
John Kessenich717c80a2018-08-23 15:17:10 -06008484 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008485 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008486
GregFcd1f1692017-09-21 18:40:22 -06008487#endif
8488
John Kessenich4e11b612018-08-30 16:56:59 -06008489 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008490}
8491
8492}; // end namespace glslang