blob: 75357ae4a327d67a337002a24e6c59b019e3c723 [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 Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 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 Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600173 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
174 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
176
John Kessenichead86222018-03-28 18:01:20 -0600177 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
178 glslang::TBasicType typeProxy, bool reduceComparison = true);
179 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
180 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500181 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600182 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600186 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500188 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
Rex Xu51596642016-09-21 18:56:12 +0800189 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800190 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600192 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800193 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700195#ifdef NV_EXTENSIONS
196 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
197#endif
qining08408382016-03-21 09:51:37 -0400198 spv::Id createSpvConstant(const glslang::TIntermTyped&);
199 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600200 bool isTrivialLeaf(const glslang::TIntermTyped* node);
201 bool isTrivial(const glslang::TIntermTyped* node);
202 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500203#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800204 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700206 void addPre13Extension(const char* ext)
207 {
208 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
209 builder.addExtension(ext);
210 }
John Kessenich9c14f772019-06-17 08:38:35 -0600211 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
212 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500213 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600214
John Kessenich121853f2017-05-31 17:11:16 -0600215 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600217 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700218 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600219 int sequenceDepth;
220
Lei Zhang17535f72016-05-04 15:55:59 -0400221 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400222
John Kessenich140f3df2015-06-26 16:58:36 -0600223 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
224 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700225 bool inEntryPoint;
226 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700227 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700228 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600229 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600230 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600231 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800232 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600233
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600235 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600236 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700237 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700238 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
239 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700241 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600242 // Map pointee types for EbtReference to their forward pointers
243 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600244 // Type forcing, for when SPIR-V wants a different type than the AST,
245 // requiring local translation to and from SPIR-V type on every access.
246 // Maps <builtin-variable-id -> AST-required-type-id>
247 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600248};
249
250//
251// Helper functions for translating glslang representations to SPIR-V enumerants.
252//
253
254// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700255spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600256{
John Kessenich66e2faf2016-03-12 18:34:36 -0700257 switch (source) {
258 case glslang::EShSourceGlsl:
259 switch (profile) {
260 case ENoProfile:
261 case ECoreProfile:
262 case ECompatibilityProfile:
263 return spv::SourceLanguageGLSL;
264 case EEsProfile:
265 return spv::SourceLanguageESSL;
266 default:
267 return spv::SourceLanguageUnknown;
268 }
269 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600270 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600271 default:
272 return spv::SourceLanguageUnknown;
273 }
274}
275
276// Translate glslang language (stage) to SPIR-V execution model.
277spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
278{
279 switch (stage) {
280 case EShLangVertex: return spv::ExecutionModelVertex;
281 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
282 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
283 case EShLangGeometry: return spv::ExecutionModelGeometry;
284 case EShLangFragment: return spv::ExecutionModelFragment;
285 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700286#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700287 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
288 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
289 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
290 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
291 case EShLangMissNV: return spv::ExecutionModelMissNV;
292 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700293 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
294 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
295#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600296 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700297 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600298 return spv::ExecutionModelFragment;
299 }
300}
301
John Kessenich140f3df2015-06-26 16:58:36 -0600302// Translate glslang sampler type to SPIR-V dimensionality.
303spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
304{
305 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700306 case glslang::Esd1D: return spv::Dim1D;
307 case glslang::Esd2D: return spv::Dim2D;
308 case glslang::Esd3D: return spv::Dim3D;
309 case glslang::EsdCube: return spv::DimCube;
310 case glslang::EsdRect: return spv::DimRect;
311 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700312 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600313 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700314 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return spv::Dim2D;
316 }
317}
318
John Kessenichf6640762016-08-01 19:44:00 -0600319// Translate glslang precision to SPIR-V precision decorations.
320spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600321{
John Kessenichf6640762016-08-01 19:44:00 -0600322 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700323 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600324 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600325 default:
326 return spv::NoPrecision;
327 }
328}
329
John Kessenichf6640762016-08-01 19:44:00 -0600330// Translate glslang type to SPIR-V precision decorations.
331spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
332{
333 return TranslatePrecisionDecoration(type.getQualifier().precision);
334}
335
John Kessenich140f3df2015-06-26 16:58:36 -0600336// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600337spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600338{
339 if (type.getBasicType() == glslang::EbtBlock) {
340 switch (type.getQualifier().storage) {
341 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600342 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 case glslang::EvqVaryingIn: return spv::DecorationBlock;
344 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700345#ifdef NV_EXTENSIONS
346 case glslang::EvqPayloadNV: return spv::DecorationBlock;
347 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
348 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700349 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
350 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700351#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600352 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700353 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600354 break;
355 }
356 }
357
John Kessenich4016e382016-07-15 11:53:56 -0600358 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600359}
360
Rex Xu1da878f2016-02-21 20:59:01 +0800361// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500362void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800363{
Jeff Bolz36831c92018-09-05 10:11:41 -0500364 if (!useVulkanMemoryModel) {
365 if (qualifier.coherent)
366 memory.push_back(spv::DecorationCoherent);
367 if (qualifier.volatil) {
368 memory.push_back(spv::DecorationVolatile);
369 memory.push_back(spv::DecorationCoherent);
370 }
John Kessenich14b85d32018-06-04 15:36:03 -0600371 }
Rex Xu1da878f2016-02-21 20:59:01 +0800372 if (qualifier.restrict)
373 memory.push_back(spv::DecorationRestrict);
374 if (qualifier.readonly)
375 memory.push_back(spv::DecorationNonWritable);
376 if (qualifier.writeonly)
377 memory.push_back(spv::DecorationNonReadable);
378}
379
John Kessenich140f3df2015-06-26 16:58:36 -0600380// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700381spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600382{
383 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700384 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600385 case glslang::ElmRowMajor:
386 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700387 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600388 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700389 default:
390 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600391 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600392 }
393 } else {
394 switch (type.getBasicType()) {
395 default:
John Kessenich4016e382016-07-15 11:53:56 -0600396 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600397 break;
398 case glslang::EbtBlock:
399 switch (type.getQualifier().storage) {
400 case glslang::EvqUniform:
401 case glslang::EvqBuffer:
402 switch (type.getQualifier().layoutPacking) {
403 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600404 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
405 default:
John Kessenich4016e382016-07-15 11:53:56 -0600406 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 }
408 case glslang::EvqVaryingIn:
409 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700410 if (type.getQualifier().isTaskMemory()) {
411 switch (type.getQualifier().layoutPacking) {
412 case glslang::ElpShared: return spv::DecorationGLSLShared;
413 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
414 default: break;
415 }
416 } else {
417 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
418 }
John Kessenich4016e382016-07-15 11:53:56 -0600419 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700420#ifdef NV_EXTENSIONS
421 case glslang::EvqPayloadNV:
422 case glslang::EvqPayloadInNV:
423 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700424 case glslang::EvqCallableDataNV:
425 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700426 return spv::DecorationMax;
427#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600428 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700429 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431 }
432 }
433 }
434}
435
436// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600437// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700438// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800439spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600440{
Rex Xubbceed72016-05-21 09:40:44 +0800441 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700442 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600443 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600444 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700445 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700446 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600447 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800448#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800449 else if (qualifier.explicitInterp) {
450 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800451 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800452 }
Rex Xu9d93a232016-05-05 12:30:44 +0800453#endif
Rex Xubbceed72016-05-21 09:40:44 +0800454 else
John Kessenich4016e382016-07-15 11:53:56 -0600455 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800456}
457
458// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600459// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800460// should be applied.
461spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
462{
463 if (qualifier.patch)
464 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700465 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600466 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700467 else if (qualifier.sample) {
468 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600469 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700470 } else
John Kessenich4016e382016-07-15 11:53:56 -0600471 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600472}
473
John Kessenich92187592016-02-01 13:45:25 -0700474// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700475spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600476{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700477 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600478 return spv::DecorationInvariant;
479 else
John Kessenich4016e382016-07-15 11:53:56 -0600480 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600481}
482
qining9220dbb2016-05-04 17:34:38 -0400483// If glslang type is noContraction, return SPIR-V NoContraction decoration.
484spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
485{
486 if (qualifier.noContraction)
487 return spv::DecorationNoContraction;
488 else
John Kessenich4016e382016-07-15 11:53:56 -0600489 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400490}
491
John Kessenich5611c6d2018-04-05 11:25:02 -0600492// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
493spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
494{
495 if (qualifier.isNonUniform()) {
496 builder.addExtension("SPV_EXT_descriptor_indexing");
497 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
498 return spv::DecorationNonUniformEXT;
499 } else
500 return spv::DecorationMax;
501}
502
Jeff Bolz36831c92018-09-05 10:11:41 -0500503spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
504{
505 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
506 return spv::MemoryAccessMaskNone;
507 }
508 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
509 if (coherentFlags.volatil ||
510 coherentFlags.coherent ||
511 coherentFlags.devicecoherent ||
512 coherentFlags.queuefamilycoherent ||
513 coherentFlags.workgroupcoherent ||
514 coherentFlags.subgroupcoherent) {
515 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
516 spv::MemoryAccessMakePointerVisibleKHRMask;
517 }
518 if (coherentFlags.nonprivate) {
519 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
520 }
521 if (coherentFlags.volatil) {
522 mask = mask | spv::MemoryAccessVolatileMask;
523 }
524 if (mask != spv::MemoryAccessMaskNone) {
525 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
526 }
527 return mask;
528}
529
530spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
531{
532 if (!glslangIntermediate->usingVulkanMemoryModel()) {
533 return spv::ImageOperandsMaskNone;
534 }
535 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
536 if (coherentFlags.volatil ||
537 coherentFlags.coherent ||
538 coherentFlags.devicecoherent ||
539 coherentFlags.queuefamilycoherent ||
540 coherentFlags.workgroupcoherent ||
541 coherentFlags.subgroupcoherent) {
542 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
543 spv::ImageOperandsMakeTexelVisibleKHRMask;
544 }
545 if (coherentFlags.nonprivate) {
546 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
547 }
548 if (coherentFlags.volatil) {
549 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
550 }
551 if (mask != spv::ImageOperandsMaskNone) {
552 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
553 }
554 return mask;
555}
556
557spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
558{
559 spv::Builder::AccessChain::CoherentFlags flags;
560 flags.coherent = type.getQualifier().coherent;
561 flags.devicecoherent = type.getQualifier().devicecoherent;
562 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
563 // shared variables are implicitly workgroupcoherent in GLSL.
564 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
565 type.getQualifier().storage == glslang::EvqShared;
566 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600567 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 // *coherent variables are implicitly nonprivate in GLSL
569 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500570 flags.subgroupcoherent ||
571 flags.workgroupcoherent ||
572 flags.queuefamilycoherent ||
573 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600574 flags.coherent ||
575 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 flags.isImage = type.getBasicType() == glslang::EbtSampler;
577 return flags;
578}
579
580spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
581{
582 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600583 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500584 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
585 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
586 } else if (coherentFlags.devicecoherent) {
587 scope = spv::ScopeDevice;
588 } else if (coherentFlags.queuefamilycoherent) {
589 scope = spv::ScopeQueueFamilyKHR;
590 } else if (coherentFlags.workgroupcoherent) {
591 scope = spv::ScopeWorkgroup;
592 } else if (coherentFlags.subgroupcoherent) {
593 scope = spv::ScopeSubgroup;
594 } else {
595 scope = spv::ScopeMax;
596 }
597 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
598 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
599 }
600 return scope;
601}
602
David Netoa901ffe2016-06-08 14:11:40 +0100603// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
604// associated capabilities when required. For some built-in variables, a capability
605// is generated only when using the variable in an executable instruction, but not when
606// just declaring a struct member variable with it. This is true for PointSize,
607// ClipDistance, and CullDistance.
608spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600609{
610 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700611 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600612 // Defer adding the capability until the built-in is actually used.
613 if (! memberDeclaration) {
614 switch (glslangIntermediate->getStage()) {
615 case EShLangGeometry:
616 builder.addCapability(spv::CapabilityGeometryPointSize);
617 break;
618 case EShLangTessControl:
619 case EShLangTessEvaluation:
620 builder.addCapability(spv::CapabilityTessellationPointSize);
621 break;
622 default:
623 break;
624 }
John Kessenich92187592016-02-01 13:45:25 -0700625 }
626 return spv::BuiltInPointSize;
627
John Kessenichebb50532016-05-16 19:22:05 -0600628 // These *Distance capabilities logically belong here, but if the member is declared and
629 // then never used, consumers of SPIR-V prefer the capability not be declared.
630 // They are now generated when used, rather than here when declared.
631 // Potentially, the specification should be more clear what the minimum
632 // use needed is to trigger the capability.
633 //
John Kessenich92187592016-02-01 13:45:25 -0700634 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100635 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800636 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700637 return spv::BuiltInClipDistance;
638
639 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100640 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800641 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700642 return spv::BuiltInCullDistance;
643
644 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600645 builder.addCapability(spv::CapabilityMultiViewport);
646 if (glslangIntermediate->getStage() == EShLangVertex ||
647 glslangIntermediate->getStage() == EShLangTessControl ||
648 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800649
John Kessenichba6a3c22017-09-13 13:22:50 -0600650 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
651 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800652 }
John Kessenich92187592016-02-01 13:45:25 -0700653 return spv::BuiltInViewportIndex;
654
John Kessenich5e801132016-02-15 11:09:46 -0700655 case glslang::EbvSampleId:
656 builder.addCapability(spv::CapabilitySampleRateShading);
657 return spv::BuiltInSampleId;
658
659 case glslang::EbvSamplePosition:
660 builder.addCapability(spv::CapabilitySampleRateShading);
661 return spv::BuiltInSamplePosition;
662
663 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700664 return spv::BuiltInSampleMask;
665
John Kessenich78a45572016-07-08 14:05:15 -0600666 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700667#ifdef NV_EXTENSIONS
668 if (glslangIntermediate->getStage() == EShLangMeshNV) {
669 return spv::BuiltInLayer;
670 }
671#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600672 builder.addCapability(spv::CapabilityGeometry);
673 if (glslangIntermediate->getStage() == EShLangVertex ||
674 glslangIntermediate->getStage() == EShLangTessControl ||
675 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800676
John Kessenichba6a3c22017-09-13 13:22:50 -0600677 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
678 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800679 }
John Kessenich78a45572016-07-08 14:05:15 -0600680 return spv::BuiltInLayer;
681
John Kessenich140f3df2015-06-26 16:58:36 -0600682 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600683 case glslang::EbvVertexId: return spv::BuiltInVertexId;
684 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700685 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
686 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800687
John Kessenichda581a22015-10-14 14:10:30 -0600688 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700689 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800690 builder.addCapability(spv::CapabilityDrawParameters);
691 return spv::BuiltInBaseVertex;
692
John Kessenichda581a22015-10-14 14:10:30 -0600693 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700694 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800695 builder.addCapability(spv::CapabilityDrawParameters);
696 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200697
John Kessenichda581a22015-10-14 14:10:30 -0600698 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700699 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800700 builder.addCapability(spv::CapabilityDrawParameters);
701 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200702
703 case glslang::EbvPrimitiveId:
704 if (glslangIntermediate->getStage() == EShLangFragment)
705 builder.addCapability(spv::CapabilityGeometry);
706 return spv::BuiltInPrimitiveId;
707
Rex Xu37cdcee2017-06-29 17:46:34 +0800708 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800709 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
710 builder.addCapability(spv::CapabilityStencilExportEXT);
711 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800712
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600714 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
715 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
716 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
717 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
718 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
719 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
720 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600721 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
722 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
723 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
724 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
725 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
726 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
727 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
728 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800729
Rex Xu574ab042016-04-14 16:53:07 +0800730 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800731 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800732 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
733 return spv::BuiltInSubgroupSize;
734
Rex Xu574ab042016-04-14 16:53:07 +0800735 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800736 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800737 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
738 return spv::BuiltInSubgroupLocalInvocationId;
739
Rex Xu574ab042016-04-14 16:53:07 +0800740 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800741 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
742 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600743 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800744
Rex Xu574ab042016-04-14 16:53:07 +0800745 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800746 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
747 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600748 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800749
Rex Xu574ab042016-04-14 16:53:07 +0800750 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800751 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
752 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600753 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800754
Rex Xu574ab042016-04-14 16:53:07 +0800755 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800756 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
757 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600758 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800759
Rex Xu574ab042016-04-14 16:53:07 +0800760 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800761 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
762 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600763 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800764
John Kessenich66011cb2018-03-06 16:12:04 -0700765 case glslang::EbvNumSubgroups:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInNumSubgroups;
768
769 case glslang::EbvSubgroupID:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupId;
772
773 case glslang::EbvSubgroupSize2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 return spv::BuiltInSubgroupSize;
776
777 case glslang::EbvSubgroupInvocation2:
778 builder.addCapability(spv::CapabilityGroupNonUniform);
779 return spv::BuiltInSubgroupLocalInvocationId;
780
781 case glslang::EbvSubgroupEqMask2:
782 builder.addCapability(spv::CapabilityGroupNonUniform);
783 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
784 return spv::BuiltInSubgroupEqMask;
785
786 case glslang::EbvSubgroupGeMask2:
787 builder.addCapability(spv::CapabilityGroupNonUniform);
788 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
789 return spv::BuiltInSubgroupGeMask;
790
791 case glslang::EbvSubgroupGtMask2:
792 builder.addCapability(spv::CapabilityGroupNonUniform);
793 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
794 return spv::BuiltInSubgroupGtMask;
795
796 case glslang::EbvSubgroupLeMask2:
797 builder.addCapability(spv::CapabilityGroupNonUniform);
798 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
799 return spv::BuiltInSubgroupLeMask;
800
801 case glslang::EbvSubgroupLtMask2:
802 builder.addCapability(spv::CapabilityGroupNonUniform);
803 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
804 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600805
Rex Xu9d93a232016-05-05 12:30:44 +0800806#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800807 case glslang::EbvBaryCoordNoPersp:
808 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
809 return spv::BuiltInBaryCoordNoPerspAMD;
810
811 case glslang::EbvBaryCoordNoPerspCentroid:
812 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
813 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
814
815 case glslang::EbvBaryCoordNoPerspSample:
816 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
817 return spv::BuiltInBaryCoordNoPerspSampleAMD;
818
819 case glslang::EbvBaryCoordSmooth:
820 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
821 return spv::BuiltInBaryCoordSmoothAMD;
822
823 case glslang::EbvBaryCoordSmoothCentroid:
824 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
825 return spv::BuiltInBaryCoordSmoothCentroidAMD;
826
827 case glslang::EbvBaryCoordSmoothSample:
828 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
829 return spv::BuiltInBaryCoordSmoothSampleAMD;
830
831 case glslang::EbvBaryCoordPullModel:
832 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
833 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800834#endif
chaoc771d89f2017-01-13 01:10:53 -0800835
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700837 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700838 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700839 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700840
841 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700842 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700843 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700844 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700845
Daniel Koch5154db52018-11-26 10:01:58 -0500846 case glslang::EbvFragSizeEXT:
847 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
848 builder.addCapability(spv::CapabilityFragmentDensityEXT);
849 return spv::BuiltInFragSizeEXT;
850
851 case glslang::EbvFragInvocationCountEXT:
852 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
853 builder.addCapability(spv::CapabilityFragmentDensityEXT);
854 return spv::BuiltInFragInvocationCountEXT;
855
chaoc771d89f2017-01-13 01:10:53 -0800856#ifdef NV_EXTENSIONS
857 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800858 if (!memberDeclaration) {
859 builder.addExtension(spv::E_SPV_NV_viewport_array2);
860 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
861 }
chaoc771d89f2017-01-13 01:10:53 -0800862 return spv::BuiltInViewportMaskNV;
863 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800864 if (!memberDeclaration) {
865 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
866 builder.addCapability(spv::CapabilityShaderStereoViewNV);
867 }
chaoc771d89f2017-01-13 01:10:53 -0800868 return spv::BuiltInSecondaryPositionNV;
869 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800870 if (!memberDeclaration) {
871 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
872 builder.addCapability(spv::CapabilityShaderStereoViewNV);
873 }
chaoc771d89f2017-01-13 01:10:53 -0800874 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800875 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800876 if (!memberDeclaration) {
877 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
878 builder.addCapability(spv::CapabilityPerViewAttributesNV);
879 }
chaocdf3956c2017-02-14 14:52:34 -0800880 return spv::BuiltInPositionPerViewNV;
881 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800882 if (!memberDeclaration) {
883 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
884 builder.addCapability(spv::CapabilityPerViewAttributesNV);
885 }
chaocdf3956c2017-02-14 14:52:34 -0800886 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700887 case glslang::EbvFragFullyCoveredNV:
888 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
889 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
890 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700891 case glslang::EbvFragmentSizeNV:
892 builder.addExtension(spv::E_SPV_NV_shading_rate);
893 builder.addCapability(spv::CapabilityShadingRateNV);
894 return spv::BuiltInFragmentSizeNV;
895 case glslang::EbvInvocationsPerPixelNV:
896 builder.addExtension(spv::E_SPV_NV_shading_rate);
897 builder.addCapability(spv::CapabilityShadingRateNV);
898 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700899
Daniel Koch593a4e02019-05-27 16:46:31 -0400900 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700901 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700902 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700903 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700904 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700905 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700906 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700907 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700908 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700909 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700910 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700911 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700912 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700913 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700914 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700915 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700916 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700917 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700918 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700919 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700920 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700921 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700922 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700923 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700924 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700925 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700926 return spv::BuiltInWorldToObjectNV;
927 case glslang::EbvIncomingRayFlagsNV:
928 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400929
930 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700931 case glslang::EbvBaryCoordNV:
932 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
933 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
934 return spv::BuiltInBaryCoordNV;
935 case glslang::EbvBaryCoordNoPerspNV:
936 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
937 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
938 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400939
940 // mesh shaders
941 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700942 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400943 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700944 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400945 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700946 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400947 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700948 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400949 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700950 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400951 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700952 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400953 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700954 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400955 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700956 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400957#endif
Daniel Koch2cb2f192019-06-04 08:43:32 -0400958
959 // sm builtins
960 case glslang::EbvWarpsPerSM:
961 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
962 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
963 return spv::BuiltInWarpsPerSMNV;
964 case glslang::EbvSMCount:
965 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
966 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
967 return spv::BuiltInSMCountNV;
968 case glslang::EbvWarpID:
969 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
970 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
971 return spv::BuiltInWarpIDNV;
972 case glslang::EbvSMID:
973 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
974 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
975 return spv::BuiltInSMIDNV;
Rex Xu3e783f92017-02-22 16:44:48 +0800976 default:
977 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600978 }
979}
980
Rex Xufc618912015-09-09 16:42:49 +0800981// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700982spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800983{
984 assert(type.getBasicType() == glslang::EbtSampler);
985
John Kessenich5d0fa972016-02-15 11:57:00 -0700986 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -0600987 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -0700988 case glslang::ElfRg32f:
989 case glslang::ElfRg16f:
990 case glslang::ElfR11fG11fB10f:
991 case glslang::ElfR16f:
992 case glslang::ElfRgba16:
993 case glslang::ElfRgb10A2:
994 case glslang::ElfRg16:
995 case glslang::ElfRg8:
996 case glslang::ElfR16:
997 case glslang::ElfR8:
998 case glslang::ElfRgba16Snorm:
999 case glslang::ElfRg16Snorm:
1000 case glslang::ElfRg8Snorm:
1001 case glslang::ElfR16Snorm:
1002 case glslang::ElfR8Snorm:
1003
1004 case glslang::ElfRg32i:
1005 case glslang::ElfRg16i:
1006 case glslang::ElfRg8i:
1007 case glslang::ElfR16i:
1008 case glslang::ElfR8i:
1009
1010 case glslang::ElfRgb10a2ui:
1011 case glslang::ElfRg32ui:
1012 case glslang::ElfRg16ui:
1013 case glslang::ElfRg8ui:
1014 case glslang::ElfR16ui:
1015 case glslang::ElfR8ui:
1016 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1017 break;
1018
1019 default:
1020 break;
1021 }
1022
1023 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001024 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001025 case glslang::ElfNone: return spv::ImageFormatUnknown;
1026 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1027 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1028 case glslang::ElfR32f: return spv::ImageFormatR32f;
1029 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1030 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1031 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1032 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1033 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1034 case glslang::ElfR16f: return spv::ImageFormatR16f;
1035 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1036 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1037 case glslang::ElfRg16: return spv::ImageFormatRg16;
1038 case glslang::ElfRg8: return spv::ImageFormatRg8;
1039 case glslang::ElfR16: return spv::ImageFormatR16;
1040 case glslang::ElfR8: return spv::ImageFormatR8;
1041 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1042 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1043 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1044 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1045 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1046 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1047 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1048 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1049 case glslang::ElfR32i: return spv::ImageFormatR32i;
1050 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1051 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1052 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1053 case glslang::ElfR16i: return spv::ImageFormatR16i;
1054 case glslang::ElfR8i: return spv::ImageFormatR8i;
1055 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1056 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1057 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1058 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1059 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1060 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1061 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1062 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1063 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1064 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001065 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001066 }
1067}
1068
John Kesseniche18fd202018-01-30 11:01:39 -07001069spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001070{
John Kesseniche18fd202018-01-30 11:01:39 -07001071 if (selectionNode.getFlatten())
1072 return spv::SelectionControlFlattenMask;
1073 if (selectionNode.getDontFlatten())
1074 return spv::SelectionControlDontFlattenMask;
1075 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001076}
1077
John Kesseniche18fd202018-01-30 11:01:39 -07001078spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001079{
John Kesseniche18fd202018-01-30 11:01:39 -07001080 if (switchNode.getFlatten())
1081 return spv::SelectionControlFlattenMask;
1082 if (switchNode.getDontFlatten())
1083 return spv::SelectionControlDontFlattenMask;
1084 return spv::SelectionControlMaskNone;
1085}
1086
John Kessenicha2858d92018-01-31 08:11:18 -07001087// return a non-0 dependency if the dependency argument must be set
1088spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001089 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001090{
1091 spv::LoopControlMask control = spv::LoopControlMaskNone;
1092
1093 if (loopNode.getDontUnroll())
1094 control = control | spv::LoopControlDontUnrollMask;
1095 if (loopNode.getUnroll())
1096 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001097 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001098 control = control | spv::LoopControlDependencyInfiniteMask;
1099 else if (loopNode.getLoopDependency() > 0) {
1100 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001101 operands.push_back((unsigned int)loopNode.getLoopDependency());
1102 }
1103 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1104 if (loopNode.getMinIterations() > 0) {
1105 control = control | spv::LoopControlMinIterationsMask;
1106 operands.push_back(loopNode.getMinIterations());
1107 }
1108 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1109 control = control | spv::LoopControlMaxIterationsMask;
1110 operands.push_back(loopNode.getMaxIterations());
1111 }
1112 if (loopNode.getIterationMultiple() > 1) {
1113 control = control | spv::LoopControlIterationMultipleMask;
1114 operands.push_back(loopNode.getIterationMultiple());
1115 }
1116 if (loopNode.getPeelCount() > 0) {
1117 control = control | spv::LoopControlPeelCountMask;
1118 operands.push_back(loopNode.getPeelCount());
1119 }
1120 if (loopNode.getPartialCount() > 0) {
1121 control = control | spv::LoopControlPartialCountMask;
1122 operands.push_back(loopNode.getPartialCount());
1123 }
John Kessenicha2858d92018-01-31 08:11:18 -07001124 }
John Kesseniche18fd202018-01-30 11:01:39 -07001125
1126 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001127}
1128
John Kessenicha5c5fb62017-05-05 05:09:58 -06001129// Translate glslang type to SPIR-V storage class.
1130spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1131{
1132 if (type.getQualifier().isPipeInput())
1133 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001134 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001135 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001136
1137 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1138 type.getQualifier().storage == glslang::EvqUniform) {
1139 if (type.getBasicType() == glslang::EbtAtomicUint)
1140 return spv::StorageClassAtomicCounter;
1141 if (type.containsOpaque())
1142 return spv::StorageClassUniformConstant;
1143 }
1144
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001145#ifdef NV_EXTENSIONS
1146 if (type.getQualifier().isUniformOrBuffer() &&
1147 type.getQualifier().layoutShaderRecordNV) {
1148 return spv::StorageClassShaderRecordBufferNV;
1149 }
1150#endif
1151
John Kessenichbed4e4f2017-09-08 02:38:07 -06001152 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001153 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001154 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001155 }
1156
1157 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001158 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001159 return spv::StorageClassPushConstant;
1160 if (type.getBasicType() == glslang::EbtBlock)
1161 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001162 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001163 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001164
1165 switch (type.getQualifier().storage) {
1166 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1167 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1168 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1169 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001170#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001171 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1172 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1173 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1174 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1175 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001176#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001177 default:
1178 assert(0);
1179 break;
1180 }
1181
1182 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001183}
1184
John Kessenich5611c6d2018-04-05 11:25:02 -06001185// Add capabilities pertaining to how an array is indexed.
1186void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1187 const glslang::TType& indexType)
1188{
1189 if (indexType.getQualifier().isNonUniform()) {
1190 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001191 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001192 if (baseType.getBasicType() == glslang::EbtSampler) {
1193 if (baseType.getQualifier().hasAttachment())
1194 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1195 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1196 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1197 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1198 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1199 else if (baseType.isImage())
1200 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1201 else if (baseType.isTexture())
1202 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1203 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1204 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1205 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1206 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1207 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1208 }
1209 } else {
1210 // assume a dynamically uniform index
1211 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001212 if (baseType.getQualifier().hasAttachment()) {
1213 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001214 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001215 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1216 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001217 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001218 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1219 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001220 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001221 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001222 }
1223 }
1224}
1225
qining25262b32016-05-06 17:25:16 -04001226// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001227// descriptor set.
1228bool IsDescriptorResource(const glslang::TType& type)
1229{
John Kessenichf7497e22016-03-08 21:36:22 -07001230 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001231 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001232 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001233 ! type.getQualifier().isShaderRecordNV() &&
1234 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001235
1236 // non block...
1237 // basically samplerXXX/subpass/sampler/texture are all included
1238 // if they are the global-scope-class, not the function parameter
1239 // (or local, if they ever exist) class.
1240 if (type.getBasicType() == glslang::EbtSampler)
1241 return type.getQualifier().isUniformOrBuffer();
1242
1243 // None of the above.
1244 return false;
1245}
1246
John Kesseniche0b6cad2015-12-24 10:30:13 -07001247void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1248{
1249 if (child.layoutMatrix == glslang::ElmNone)
1250 child.layoutMatrix = parent.layoutMatrix;
1251
1252 if (parent.invariant)
1253 child.invariant = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001254#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001255 if (parent.nopersp)
1256 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001257 if (parent.explicitInterp)
1258 child.explicitInterp = true;
1259#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001260 if (parent.flat)
1261 child.flat = true;
1262 if (parent.centroid)
1263 child.centroid = true;
1264 if (parent.patch)
1265 child.patch = true;
1266 if (parent.sample)
1267 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001268 if (parent.coherent)
1269 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001270 if (parent.devicecoherent)
1271 child.devicecoherent = true;
1272 if (parent.queuefamilycoherent)
1273 child.queuefamilycoherent = true;
1274 if (parent.workgroupcoherent)
1275 child.workgroupcoherent = true;
1276 if (parent.subgroupcoherent)
1277 child.subgroupcoherent = true;
1278 if (parent.nonprivate)
1279 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001280 if (parent.volatil)
1281 child.volatil = true;
1282 if (parent.restrict)
1283 child.restrict = true;
1284 if (parent.readonly)
1285 child.readonly = true;
1286 if (parent.writeonly)
1287 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001288#ifdef NV_EXTENSIONS
1289 if (parent.perPrimitiveNV)
1290 child.perPrimitiveNV = true;
1291 if (parent.perViewNV)
1292 child.perViewNV = true;
1293 if (parent.perTaskNV)
1294 child.perTaskNV = true;
1295#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001296}
1297
John Kessenichf2b7f332016-09-01 17:05:23 -06001298bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001299{
John Kessenich7b9fa252016-01-21 18:56:57 -07001300 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001301 // - struct members might inherit from a struct declaration
1302 // (note that non-block structs don't explicitly inherit,
1303 // only implicitly, meaning no decoration involved)
1304 // - affect decorations on the struct members
1305 // (note smooth does not, and expecting something like volatile
1306 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001307 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001308 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001309}
1310
John Kessenich140f3df2015-06-26 16:58:36 -06001311//
1312// Implement the TGlslangToSpvTraverser class.
1313//
1314
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001315TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001316 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1317 : TIntermTraverser(true, false, true),
1318 options(options),
1319 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001320 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001321 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001322 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001323 glslangIntermediate(glslangIntermediate),
1324 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001325{
1326 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1327
1328 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001329 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1330 glslangIntermediate->getVersion());
1331
John Kessenich121853f2017-05-31 17:11:16 -06001332 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001333 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001334 builder.setSourceFile(glslangIntermediate->getSourceFile());
1335
1336 // Set the source shader's text. If for SPV version 1.0, include
1337 // a preamble in comments stating the OpModuleProcessed instructions.
1338 // Otherwise, emit those as actual instructions.
1339 std::string text;
1340 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1341 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001342 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001343 text.append("// OpModuleProcessed ");
1344 text.append(processes[p]);
1345 text.append("\n");
1346 } else
1347 builder.addModuleProcessed(processes[p]);
1348 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001349 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001350 text.append("#line 1\n");
1351 text.append(glslangIntermediate->getSourceText());
1352 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001353 // Pass name and text for all included files
1354 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1355 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1356 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001357 }
John Kessenich140f3df2015-06-26 16:58:36 -06001358 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001359
1360 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1361 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1362
1363 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1364 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1365 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1366 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1367 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001368 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001369 memoryModel = spv::MemoryModelVulkanKHR;
1370 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001371 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001372 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001373 builder.setMemoryModel(addressingModel, memoryModel);
1374
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001375 if (glslangIntermediate->usingVariablePointers()) {
1376 builder.addCapability(spv::CapabilityVariablePointers);
1377 }
1378
John Kessenicheee9d532016-09-19 18:09:30 -06001379 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1380 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001381
1382 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001383 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1384 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001385 builder.addSourceExtension(it->c_str());
1386
1387 // Add the top-level modes for this shader.
1388
John Kessenich92187592016-02-01 13:45:25 -07001389 if (glslangIntermediate->getXfbMode()) {
1390 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001391 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001392 }
John Kessenich140f3df2015-06-26 16:58:36 -06001393
1394 unsigned int mode;
1395 switch (glslangIntermediate->getStage()) {
1396 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001397 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001398 break;
1399
steve-lunarge7412492017-03-23 11:56:07 -06001400 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001401 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001402 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001403
steve-lunarge7412492017-03-23 11:56:07 -06001404 glslang::TLayoutGeometry primitive;
1405
1406 if (glslangIntermediate->getStage() == EShLangTessControl) {
1407 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1408 primitive = glslangIntermediate->getOutputPrimitive();
1409 } else {
1410 primitive = glslangIntermediate->getInputPrimitive();
1411 }
1412
1413 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001414 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1415 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1416 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001417 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001418 }
John Kessenich4016e382016-07-15 11:53:56 -06001419 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001420 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1421
John Kesseniche6903322015-10-13 16:29:02 -06001422 switch (glslangIntermediate->getVertexSpacing()) {
1423 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1424 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1425 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001426 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001427 }
John Kessenich4016e382016-07-15 11:53:56 -06001428 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001429 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1430
1431 switch (glslangIntermediate->getVertexOrder()) {
1432 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1433 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001434 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001435 }
John Kessenich4016e382016-07-15 11:53:56 -06001436 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001437 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1438
1439 if (glslangIntermediate->getPointMode())
1440 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001441 break;
1442
1443 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001444 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001445 switch (glslangIntermediate->getInputPrimitive()) {
1446 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1447 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1448 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001449 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001450 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001451 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001452 }
John Kessenich4016e382016-07-15 11:53:56 -06001453 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001454 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001455
John Kessenich140f3df2015-06-26 16:58:36 -06001456 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1457
1458 switch (glslangIntermediate->getOutputPrimitive()) {
1459 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1460 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1461 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001462 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001463 }
John Kessenich4016e382016-07-15 11:53:56 -06001464 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001465 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1466 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1467 break;
1468
1469 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001470 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001471 if (glslangIntermediate->getPixelCenterInteger())
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001473
John Kessenich140f3df2015-06-26 16:58:36 -06001474 if (glslangIntermediate->getOriginUpperLeft())
1475 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001476 else
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001478
1479 if (glslangIntermediate->getEarlyFragmentTests())
1480 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1481
chaocc1204522017-06-30 17:14:30 -07001482 if (glslangIntermediate->getPostDepthCoverage()) {
1483 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1484 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1485 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1486 }
1487
John Kesseniche6903322015-10-13 16:29:02 -06001488 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001489 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1490 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001491 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001492 }
John Kessenich4016e382016-07-15 11:53:56 -06001493 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001494 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1495
1496 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1497 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05001498
1499 switch (glslangIntermediate->getInterlockOrdering()) {
1500 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1501 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1502 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1503 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1504 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1505 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1506 default: mode = spv::ExecutionModeMax; break;
1507 }
1508 if (mode != spv::ExecutionModeMax) {
1509 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1510 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1511 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1512 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1513 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1514 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1515 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1516 } else {
1517 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1518 }
1519 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1520 }
1521
John Kessenich140f3df2015-06-26 16:58:36 -06001522 break;
1523
1524 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001525 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001526 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1527 glslangIntermediate->getLocalSize(1),
1528 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001529#ifdef NV_EXTENSIONS
1530 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1531 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1532 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1533 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1534 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1535 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1536 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1537 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1538 }
1539#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001540 break;
1541
Chao Chen3c366992018-09-19 11:41:59 -07001542#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001543 case EShLangRayGenNV:
1544 case EShLangIntersectNV:
1545 case EShLangAnyHitNV:
1546 case EShLangClosestHitNV:
1547 case EShLangMissNV:
1548 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001549 builder.addCapability(spv::CapabilityRayTracingNV);
1550 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001551 break;
Chao Chen3c366992018-09-19 11:41:59 -07001552 case EShLangTaskNV:
1553 case EShLangMeshNV:
1554 builder.addCapability(spv::CapabilityMeshShadingNV);
1555 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1556 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1557 glslangIntermediate->getLocalSize(1),
1558 glslangIntermediate->getLocalSize(2));
1559 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1560 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1561 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1562
1563 switch (glslangIntermediate->getOutputPrimitive()) {
1564 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1565 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1566 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1567 default: mode = spv::ExecutionModeMax; break;
1568 }
1569 if (mode != spv::ExecutionModeMax)
1570 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1571 }
1572 break;
1573#endif
1574
John Kessenich140f3df2015-06-26 16:58:36 -06001575 default:
1576 break;
1577 }
John Kessenich140f3df2015-06-26 16:58:36 -06001578}
1579
John Kessenichfca82622016-11-26 13:23:20 -07001580// Finish creating SPV, after the traversal is complete.
1581void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001582{
John Kessenichf04c51b2018-08-03 15:56:12 -06001583 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001584 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001585 builder.setBuildPoint(shaderEntry->getLastBlock());
1586 builder.leaveFunction();
1587 }
1588
John Kessenich7ba63412015-12-20 17:37:07 -07001589 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001590 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1591 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001592
John Kessenich23d27752019-07-28 02:12:10 -06001593#ifndef GLSLANG_WEB
John Kessenichf04c51b2018-08-03 15:56:12 -06001594 // Add capabilities, extensions, remove unneeded decorations, etc.,
1595 // based on the resulting SPIR-V.
1596 builder.postProcess();
John Kessenich23d27752019-07-28 02:12:10 -06001597#endif
John Kessenich7ba63412015-12-20 17:37:07 -07001598}
1599
John Kessenichfca82622016-11-26 13:23:20 -07001600// Write the SPV into 'out'.
1601void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001602{
John Kessenichfca82622016-11-26 13:23:20 -07001603 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001604}
1605
1606//
1607// Implement the traversal functions.
1608//
1609// Return true from interior nodes to have the external traversal
1610// continue on to children. Return false if children were
1611// already processed.
1612//
1613
1614//
qining25262b32016-05-06 17:25:16 -04001615// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001616// - uniform/input reads
1617// - output writes
1618// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1619// - something simple that degenerates into the last bullet
1620//
1621void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1622{
qining75d1d802016-04-06 14:42:01 -04001623 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1624 if (symbol->getType().getQualifier().isSpecConstant())
1625 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1626
John Kessenich140f3df2015-06-26 16:58:36 -06001627 // getSymbolId() will set up all the IO decorations on the first call.
1628 // Formal function parameters were mapped during makeFunctions().
1629 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001630
John Kessenich7ba63412015-12-20 17:37:07 -07001631 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001632 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001633 // Consider adding to the OpEntryPoint interface list.
1634 // Only looking at structures if they have at least one member.
1635 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1636 spv::StorageClass sc = builder.getStorageClass(id);
1637 // Before SPIR-V 1.4, we only want to include Input and Output.
1638 // Starting with SPIR-V 1.4, we want all globals.
1639 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1640 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001641 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001642 }
John Kessenich5f77d862017-09-19 11:09:59 -06001643 }
John Kessenich9c14f772019-06-17 08:38:35 -06001644
1645 // If the SPIR-V type is required to be different than the AST type,
1646 // translate now from the SPIR-V type to the AST type, for the consuming
1647 // operation.
1648 // Note this turns it from an l-value to an r-value.
1649 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1650 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1651 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001652 }
1653
1654 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001655 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001656 // Prepare to generate code for the access
1657
1658 // L-value chains will be computed left to right. We're on the symbol now,
1659 // which is the left-most part of the access chain, so now is "clear" time,
1660 // followed by setting the base.
1661 builder.clearAccessChain();
1662
1663 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001664 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001665 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001666 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001667 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001668 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001669 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001670 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001671 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1672 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001673 builder.setAccessChainRValue(id);
1674 else
1675 builder.setAccessChainLValue(id);
1676 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001677
1678 // Process linkage-only nodes for any special additional interface work.
1679 if (linkageOnly) {
1680 if (glslangIntermediate->getHlslFunctionality1()) {
1681 // Map implicit counter buffers to their originating buffers, which should have been
1682 // seen by now, given earlier pruning of unused counters, and preservation of order
1683 // of declaration.
1684 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1685 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1686 // Save possible originating buffers for counter buffers, keyed by
1687 // making the potential counter-buffer name.
1688 std::string keyName = symbol->getName().c_str();
1689 keyName = glslangIntermediate->addCounterBufferName(keyName);
1690 counterOriginator[keyName] = symbol;
1691 } else {
1692 // Handle a counter buffer, by finding the saved originating buffer.
1693 std::string keyName = symbol->getName().c_str();
1694 auto it = counterOriginator.find(keyName);
1695 if (it != counterOriginator.end()) {
1696 id = getSymbolId(it->second);
1697 if (id != spv::NoResult) {
1698 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001699 if (counterId != spv::NoResult) {
1700 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001701 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001702 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001703 }
1704 }
1705 }
1706 }
1707 }
1708 }
John Kessenich140f3df2015-06-26 16:58:36 -06001709}
1710
1711bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1712{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001713 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001714
qining40887662016-04-03 22:20:42 -04001715 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1716 if (node->getType().getQualifier().isSpecConstant())
1717 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1718
John Kessenich140f3df2015-06-26 16:58:36 -06001719 // First, handle special cases
1720 switch (node->getOp()) {
1721 case glslang::EOpAssign:
1722 case glslang::EOpAddAssign:
1723 case glslang::EOpSubAssign:
1724 case glslang::EOpMulAssign:
1725 case glslang::EOpVectorTimesMatrixAssign:
1726 case glslang::EOpVectorTimesScalarAssign:
1727 case glslang::EOpMatrixTimesScalarAssign:
1728 case glslang::EOpMatrixTimesMatrixAssign:
1729 case glslang::EOpDivAssign:
1730 case glslang::EOpModAssign:
1731 case glslang::EOpAndAssign:
1732 case glslang::EOpInclusiveOrAssign:
1733 case glslang::EOpExclusiveOrAssign:
1734 case glslang::EOpLeftShiftAssign:
1735 case glslang::EOpRightShiftAssign:
1736 // A bin-op assign "a += b" means the same thing as "a = a + b"
1737 // where a is evaluated before b. For a simple assignment, GLSL
1738 // says to evaluate the left before the right. So, always, left
1739 // node then right node.
1740 {
1741 // get the left l-value, save it away
1742 builder.clearAccessChain();
1743 node->getLeft()->traverse(this);
1744 spv::Builder::AccessChain lValue = builder.getAccessChain();
1745
1746 // evaluate the right
1747 builder.clearAccessChain();
1748 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001749 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001750
1751 if (node->getOp() != glslang::EOpAssign) {
1752 // the left is also an r-value
1753 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001754 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001755
1756 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001757 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001758 TranslateNoContractionDecoration(node->getType().getQualifier()),
1759 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001760 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001761 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1762 node->getType().getBasicType());
1763
1764 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001765 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001766 }
1767
1768 // store the result
1769 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001770 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001771
1772 // assignments are expressions having an rValue after they are evaluated...
1773 builder.clearAccessChain();
1774 builder.setAccessChainRValue(rValue);
1775 }
1776 return false;
1777 case glslang::EOpIndexDirect:
1778 case glslang::EOpIndexDirectStruct:
1779 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001780 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001781 // Get the left part of the access chain.
1782 node->getLeft()->traverse(this);
1783
1784 // Add the next element in the chain
1785
David Netoa901ffe2016-06-08 14:11:40 +01001786 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001787 if (! node->getLeft()->getType().isArray() &&
1788 node->getLeft()->getType().isVector() &&
1789 node->getOp() == glslang::EOpIndexDirect) {
1790 // This is essentially a hard-coded vector swizzle of size 1,
1791 // so short circuit the access-chain stuff with a swizzle.
1792 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001793 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001794 int dummySize;
1795 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1796 TranslateCoherent(node->getLeft()->getType()),
1797 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001798 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001799
1800 // Load through a block reference is performed with a dot operator that
1801 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1802 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001803 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001804 !node->getLeft()->getType().isArray() &&
1805 node->getOp() == glslang::EOpIndexDirectStruct)
1806 {
1807 spv::Id left = accessChainLoad(node->getLeft()->getType());
1808 builder.clearAccessChain();
1809 builder.setAccessChainLValue(left);
1810 }
1811
David Netoa901ffe2016-06-08 14:11:40 +01001812 int spvIndex = glslangIndex;
1813 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1814 node->getOp() == glslang::EOpIndexDirectStruct)
1815 {
1816 // This may be, e.g., an anonymous block-member selection, which generally need
1817 // index remapping due to hidden members in anonymous blocks.
1818 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1819 assert(remapper.size() > 0);
1820 spvIndex = remapper[glslangIndex];
1821 }
John Kessenichebb50532016-05-16 19:22:05 -06001822
David Netoa901ffe2016-06-08 14:11:40 +01001823 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001824 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001825
1826 // Add capabilities here for accessing PointSize and clip/cull distance.
1827 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001828 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001829 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001830 }
1831 }
1832 return false;
1833 case glslang::EOpIndexIndirect:
1834 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001835 // Array, matrix, or vector indirection with variable index.
1836 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001837 // matrices are arrays of vectors, so will also work for a matrix.
1838 // Will use the access chain's 'component' for variable index into a vector.
1839
1840 // This adapter is building access chains left to right.
1841 // Set up the access chain to the left.
1842 node->getLeft()->traverse(this);
1843
1844 // save it so that computing the right side doesn't trash it
1845 spv::Builder::AccessChain partial = builder.getAccessChain();
1846
1847 // compute the next index in the chain
1848 builder.clearAccessChain();
1849 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001850 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001851
John Kessenich5611c6d2018-04-05 11:25:02 -06001852 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1853
John Kessenich140f3df2015-06-26 16:58:36 -06001854 // restore the saved access chain
1855 builder.setAccessChain(partial);
1856
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001857 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1858 int dummySize;
1859 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1860 TranslateCoherent(node->getLeft()->getType()),
1861 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1862 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001863 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001864 }
1865 return false;
1866 case glslang::EOpVectorSwizzle:
1867 {
1868 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001870 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001871 int dummySize;
1872 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1873 TranslateCoherent(node->getLeft()->getType()),
1874 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001875 }
1876 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001877 case glslang::EOpMatrixSwizzle:
1878 logger->missingFunctionality("matrix swizzle");
1879 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001880 case glslang::EOpLogicalOr:
1881 case glslang::EOpLogicalAnd:
1882 {
1883
1884 // These may require short circuiting, but can sometimes be done as straight
1885 // binary operations. The right operand must be short circuited if it has
1886 // side effects, and should probably be if it is complex.
1887 if (isTrivial(node->getRight()->getAsTyped()))
1888 break; // handle below as a normal binary operation
1889 // otherwise, we need to do dynamic short circuiting on the right operand
1890 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1891 builder.clearAccessChain();
1892 builder.setAccessChainRValue(result);
1893 }
1894 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001895 default:
1896 break;
1897 }
1898
1899 // Assume generic binary op...
1900
John Kessenich32cfd492016-02-02 12:37:46 -07001901 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001902 builder.clearAccessChain();
1903 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001904 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001905
John Kessenich32cfd492016-02-02 12:37:46 -07001906 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001907 builder.clearAccessChain();
1908 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001909 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001910
John Kessenich32cfd492016-02-02 12:37:46 -07001911 // get result
John Kessenichead86222018-03-28 18:01:20 -06001912 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001913 TranslateNoContractionDecoration(node->getType().getQualifier()),
1914 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001915 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001916 convertGlslangToSpvType(node->getType()), left, right,
1917 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001918
John Kessenich50e57562015-12-21 21:21:11 -07001919 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001920 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001921 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001922 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001923 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001924 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001925 return false;
1926 }
John Kessenich140f3df2015-06-26 16:58:36 -06001927}
1928
John Kessenich9c14f772019-06-17 08:38:35 -06001929// Figure out what, if any, type changes are needed when accessing a specific built-in.
1930// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1931// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1932std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1933 const glslang::TType& glslangType)
1934{
1935 switch(builtIn)
1936 {
1937 case spv::BuiltInSubgroupEqMask:
1938 case spv::BuiltInSubgroupGeMask:
1939 case spv::BuiltInSubgroupGtMask:
1940 case spv::BuiltInSubgroupLeMask:
1941 case spv::BuiltInSubgroupLtMask: {
1942 // these require changing a 64-bit scaler -> a vector of 32-bit components
1943 if (glslangType.isVector())
1944 break;
1945 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1946 builder.makeUintType(64));
1947 return ret;
1948 }
1949 default:
1950 break;
1951 }
1952
1953 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1954 return ret;
1955}
1956
1957// For an object previously identified (see getForcedType() and forceType)
1958// as needing type translations, do the translation needed for a load, turning
1959// an L-value into in R-value.
1960spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
1961{
1962 const auto forceIt = forceType.find(object);
1963 if (forceIt == forceType.end())
1964 return object;
1965
1966 spv::Id desiredTypeId = forceIt->second;
1967 spv::Id objectTypeId = builder.getTypeId(object);
1968 assert(builder.isPointerType(objectTypeId));
1969 objectTypeId = builder.getContainedTypeId(objectTypeId);
1970 if (builder.isVectorType(objectTypeId) &&
1971 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
1972 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
1973 // handle 32-bit v.xy* -> 64-bit
1974 builder.clearAccessChain();
1975 builder.setAccessChainLValue(object);
1976 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
1977 std::vector<spv::Id> components;
1978 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
1979 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
1980
1981 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
1982 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
1983 builder.createCompositeConstruct(vecType, components));
1984 } else {
1985 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
1986 }
1987 } else {
1988 logger->missingFunctionality("forcing non 32-bit vector type");
1989 }
1990
1991 return object;
1992}
1993
John Kessenich140f3df2015-06-26 16:58:36 -06001994bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1995{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001996 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001997
qining40887662016-04-03 22:20:42 -04001998 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1999 if (node->getType().getQualifier().isSpecConstant())
2000 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2001
John Kessenichfc51d282015-08-19 13:34:18 -06002002 spv::Id result = spv::NoResult;
2003
2004 // try texturing first
2005 result = createImageTextureFunctionCall(node);
2006 if (result != spv::NoResult) {
2007 builder.clearAccessChain();
2008 builder.setAccessChainRValue(result);
2009
2010 return false; // done with this node
2011 }
2012
2013 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002014
2015 if (node->getOp() == glslang::EOpArrayLength) {
2016 // Quite special; won't want to evaluate the operand.
2017
John Kessenich5611c6d2018-04-05 11:25:02 -06002018 // Currently, the front-end does not allow .length() on an array until it is sized,
2019 // except for the last block membeor of an SSBO.
2020 // TODO: If this changes, link-time sized arrays might show up here, and need their
2021 // size extracted.
2022
John Kessenichc9a80832015-09-12 12:17:44 -06002023 // Normal .length() would have been constant folded by the front-end.
2024 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002025 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002026
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002027 spv::Id length;
2028 if (node->getOperand()->getType().isCoopMat()) {
2029 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2030
2031 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2032 assert(builder.isCooperativeMatrixType(typeId));
2033
2034 length = builder.createCooperativeMatrixLength(typeId);
2035 } else {
2036 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2037 block->traverse(this);
2038 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2039 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2040 }
John Kessenichc9a80832015-09-12 12:17:44 -06002041
John Kessenich8c869672018-11-28 07:01:37 -07002042 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2043 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2044 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002045 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2046 if (builder.isInSpecConstCodeGenMode()) {
2047 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2048 } else {
2049 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2050 }
2051 }
John Kessenich8c869672018-11-28 07:01:37 -07002052
John Kessenichc9a80832015-09-12 12:17:44 -06002053 builder.clearAccessChain();
2054 builder.setAccessChainRValue(length);
2055
2056 return false;
2057 }
2058
John Kessenichfc51d282015-08-19 13:34:18 -06002059 // Start by evaluating the operand
2060
John Kessenich8c8505c2016-07-26 12:50:38 -06002061 // Does it need a swizzle inversion? If so, evaluation is inverted;
2062 // operate first on the swizzle base, then apply the swizzle.
2063 spv::Id invertedType = spv::NoType;
2064 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2065 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2066 invertedType = getInvertedSwizzleType(*node->getOperand());
2067
John Kessenich140f3df2015-06-26 16:58:36 -06002068 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002069 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002070 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002071 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002072 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002073 operandNode = node->getOperand();
2074
2075 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002076
Rex Xufc618912015-09-09 16:42:49 +08002077 spv::Id operand = spv::NoResult;
2078
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002079 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2080
Rex Xufc618912015-09-09 16:42:49 +08002081 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2082 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002083 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002084 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002085 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002086 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2087 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2088 } else
John Kessenich32cfd492016-02-02 12:37:46 -07002089 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002090
John Kessenichead86222018-03-28 18:01:20 -06002091 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002092 TranslateNoContractionDecoration(node->getType().getQualifier()),
2093 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002094
2095 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002096 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002097 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002098
2099 // if not, then possibly an operation
2100 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002101 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002102
2103 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002104 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002105 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002106 builder.addDecoration(result, decorations.nonUniform);
2107 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002108
John Kessenich140f3df2015-06-26 16:58:36 -06002109 builder.clearAccessChain();
2110 builder.setAccessChainRValue(result);
2111
2112 return false; // done with this node
2113 }
2114
2115 // it must be a special case, check...
2116 switch (node->getOp()) {
2117 case glslang::EOpPostIncrement:
2118 case glslang::EOpPostDecrement:
2119 case glslang::EOpPreIncrement:
2120 case glslang::EOpPreDecrement:
2121 {
2122 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002123 spv::Id one = 0;
2124 if (node->getBasicType() == glslang::EbtFloat)
2125 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08002126 else if (node->getBasicType() == glslang::EbtDouble)
2127 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002128 else if (node->getBasicType() == glslang::EbtFloat16)
2129 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002130 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2131 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002132 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2133 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002134 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2135 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002136 else
2137 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002138 glslang::TOperator op;
2139 if (node->getOp() == glslang::EOpPreIncrement ||
2140 node->getOp() == glslang::EOpPostIncrement)
2141 op = glslang::EOpAdd;
2142 else
2143 op = glslang::EOpSub;
2144
John Kessenichead86222018-03-28 18:01:20 -06002145 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002146 convertGlslangToSpvType(node->getType()), operand, one,
2147 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002148 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002149
2150 // The result of operation is always stored, but conditionally the
2151 // consumed result. The consumed result is always an r-value.
2152 builder.accessChainStore(result);
2153 builder.clearAccessChain();
2154 if (node->getOp() == glslang::EOpPreIncrement ||
2155 node->getOp() == glslang::EOpPreDecrement)
2156 builder.setAccessChainRValue(result);
2157 else
2158 builder.setAccessChainRValue(operand);
2159 }
2160
2161 return false;
2162
2163 case glslang::EOpEmitStreamVertex:
2164 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2165 return false;
2166 case glslang::EOpEndStreamPrimitive:
2167 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2168 return false;
2169
2170 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002171 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002172 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002173 }
John Kessenich140f3df2015-06-26 16:58:36 -06002174}
2175
Jeff Bolz53134492019-06-25 13:31:10 -05002176// Construct a composite object, recursively copying members if their types don't match
2177spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2178{
2179 for (int c = 0; c < (int)constituents.size(); ++c) {
2180 spv::Id& constituent = constituents[c];
2181 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2182 spv::Id rType = builder.getTypeId(constituent);
2183 if (lType != rType) {
2184 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2185 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2186 } else if (builder.isStructType(rType)) {
2187 std::vector<spv::Id> rTypeConstituents;
2188 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2189 for (int i = 0; i < numrTypeConstituents; ++i) {
2190 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2191 }
2192 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2193 } else {
2194 assert(builder.isArrayType(rType));
2195 std::vector<spv::Id> rTypeConstituents;
2196 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2197
2198 spv::Id elementRType = builder.getContainedTypeId(rType);
2199 for (int i = 0; i < numrTypeConstituents; ++i) {
2200 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2201 }
2202 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2203 }
2204 }
2205 }
2206 return builder.createCompositeConstruct(resultTypeId, constituents);
2207}
2208
John Kessenich140f3df2015-06-26 16:58:36 -06002209bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2210{
qining27e04a02016-04-14 16:40:20 -04002211 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2212 if (node->getType().getQualifier().isSpecConstant())
2213 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2214
John Kessenichfc51d282015-08-19 13:34:18 -06002215 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002216 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2217 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002218
2219 // try texturing
2220 result = createImageTextureFunctionCall(node);
2221 if (result != spv::NoResult) {
2222 builder.clearAccessChain();
2223 builder.setAccessChainRValue(result);
2224
2225 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002226 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002227#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002228 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002229#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002230 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002231 // "imageStore" is a special case, which has no result
2232 return false;
2233 }
John Kessenichfc51d282015-08-19 13:34:18 -06002234
John Kessenich140f3df2015-06-26 16:58:36 -06002235 glslang::TOperator binOp = glslang::EOpNull;
2236 bool reduceComparison = true;
2237 bool isMatrix = false;
2238 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002239 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002240
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002241 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2242
John Kessenich140f3df2015-06-26 16:58:36 -06002243 assert(node->getOp());
2244
John Kessenichf6640762016-08-01 19:44:00 -06002245 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002246
2247 switch (node->getOp()) {
2248 case glslang::EOpSequence:
2249 {
2250 if (preVisit)
2251 ++sequenceDepth;
2252 else
2253 --sequenceDepth;
2254
2255 if (sequenceDepth == 1) {
2256 // If this is the parent node of all the functions, we want to see them
2257 // early, so all call points have actual SPIR-V functions to reference.
2258 // In all cases, still let the traverser visit the children for us.
2259 makeFunctions(node->getAsAggregate()->getSequence());
2260
John Kessenich6fccb3c2016-09-19 16:01:41 -06002261 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002262 // anything else gets there, so visit out of order, doing them all now.
2263 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2264
John Kessenich6a60c2f2016-12-08 21:01:59 -07002265 // 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 -06002266 // so do them manually.
2267 visitFunctions(node->getAsAggregate()->getSequence());
2268
2269 return false;
2270 }
2271
2272 return true;
2273 }
2274 case glslang::EOpLinkerObjects:
2275 {
2276 if (visit == glslang::EvPreVisit)
2277 linkageOnly = true;
2278 else
2279 linkageOnly = false;
2280
2281 return true;
2282 }
2283 case glslang::EOpComma:
2284 {
2285 // processing from left to right naturally leaves the right-most
2286 // lying around in the access chain
2287 glslang::TIntermSequence& glslangOperands = node->getSequence();
2288 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2289 glslangOperands[i]->traverse(this);
2290
2291 return false;
2292 }
2293 case glslang::EOpFunction:
2294 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002295 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002296 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002297 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002298 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002299 } else {
2300 handleFunctionEntry(node);
2301 }
2302 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002303 if (inEntryPoint)
2304 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002305 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002306 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002307 }
2308
2309 return true;
2310 case glslang::EOpParameters:
2311 // Parameters will have been consumed by EOpFunction processing, but not
2312 // the body, so we still visited the function node's children, making this
2313 // child redundant.
2314 return false;
2315 case glslang::EOpFunctionCall:
2316 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002317 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002318 if (node->isUserDefined())
2319 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002320 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07002321 if (result) {
2322 builder.clearAccessChain();
2323 builder.setAccessChainRValue(result);
2324 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002325 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002326
2327 return false;
2328 }
2329 case glslang::EOpConstructMat2x2:
2330 case glslang::EOpConstructMat2x3:
2331 case glslang::EOpConstructMat2x4:
2332 case glslang::EOpConstructMat3x2:
2333 case glslang::EOpConstructMat3x3:
2334 case glslang::EOpConstructMat3x4:
2335 case glslang::EOpConstructMat4x2:
2336 case glslang::EOpConstructMat4x3:
2337 case glslang::EOpConstructMat4x4:
2338 case glslang::EOpConstructDMat2x2:
2339 case glslang::EOpConstructDMat2x3:
2340 case glslang::EOpConstructDMat2x4:
2341 case glslang::EOpConstructDMat3x2:
2342 case glslang::EOpConstructDMat3x3:
2343 case glslang::EOpConstructDMat3x4:
2344 case glslang::EOpConstructDMat4x2:
2345 case glslang::EOpConstructDMat4x3:
2346 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002347 case glslang::EOpConstructIMat2x2:
2348 case glslang::EOpConstructIMat2x3:
2349 case glslang::EOpConstructIMat2x4:
2350 case glslang::EOpConstructIMat3x2:
2351 case glslang::EOpConstructIMat3x3:
2352 case glslang::EOpConstructIMat3x4:
2353 case glslang::EOpConstructIMat4x2:
2354 case glslang::EOpConstructIMat4x3:
2355 case glslang::EOpConstructIMat4x4:
2356 case glslang::EOpConstructUMat2x2:
2357 case glslang::EOpConstructUMat2x3:
2358 case glslang::EOpConstructUMat2x4:
2359 case glslang::EOpConstructUMat3x2:
2360 case glslang::EOpConstructUMat3x3:
2361 case glslang::EOpConstructUMat3x4:
2362 case glslang::EOpConstructUMat4x2:
2363 case glslang::EOpConstructUMat4x3:
2364 case glslang::EOpConstructUMat4x4:
2365 case glslang::EOpConstructBMat2x2:
2366 case glslang::EOpConstructBMat2x3:
2367 case glslang::EOpConstructBMat2x4:
2368 case glslang::EOpConstructBMat3x2:
2369 case glslang::EOpConstructBMat3x3:
2370 case glslang::EOpConstructBMat3x4:
2371 case glslang::EOpConstructBMat4x2:
2372 case glslang::EOpConstructBMat4x3:
2373 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002374 case glslang::EOpConstructF16Mat2x2:
2375 case glslang::EOpConstructF16Mat2x3:
2376 case glslang::EOpConstructF16Mat2x4:
2377 case glslang::EOpConstructF16Mat3x2:
2378 case glslang::EOpConstructF16Mat3x3:
2379 case glslang::EOpConstructF16Mat3x4:
2380 case glslang::EOpConstructF16Mat4x2:
2381 case glslang::EOpConstructF16Mat4x3:
2382 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002383 isMatrix = true;
2384 // fall through
2385 case glslang::EOpConstructFloat:
2386 case glslang::EOpConstructVec2:
2387 case glslang::EOpConstructVec3:
2388 case glslang::EOpConstructVec4:
2389 case glslang::EOpConstructDouble:
2390 case glslang::EOpConstructDVec2:
2391 case glslang::EOpConstructDVec3:
2392 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002393 case glslang::EOpConstructFloat16:
2394 case glslang::EOpConstructF16Vec2:
2395 case glslang::EOpConstructF16Vec3:
2396 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002397 case glslang::EOpConstructBool:
2398 case glslang::EOpConstructBVec2:
2399 case glslang::EOpConstructBVec3:
2400 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002401 case glslang::EOpConstructInt8:
2402 case glslang::EOpConstructI8Vec2:
2403 case glslang::EOpConstructI8Vec3:
2404 case glslang::EOpConstructI8Vec4:
2405 case glslang::EOpConstructUint8:
2406 case glslang::EOpConstructU8Vec2:
2407 case glslang::EOpConstructU8Vec3:
2408 case glslang::EOpConstructU8Vec4:
2409 case glslang::EOpConstructInt16:
2410 case glslang::EOpConstructI16Vec2:
2411 case glslang::EOpConstructI16Vec3:
2412 case glslang::EOpConstructI16Vec4:
2413 case glslang::EOpConstructUint16:
2414 case glslang::EOpConstructU16Vec2:
2415 case glslang::EOpConstructU16Vec3:
2416 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002417 case glslang::EOpConstructInt:
2418 case glslang::EOpConstructIVec2:
2419 case glslang::EOpConstructIVec3:
2420 case glslang::EOpConstructIVec4:
2421 case glslang::EOpConstructUint:
2422 case glslang::EOpConstructUVec2:
2423 case glslang::EOpConstructUVec3:
2424 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002425 case glslang::EOpConstructInt64:
2426 case glslang::EOpConstructI64Vec2:
2427 case glslang::EOpConstructI64Vec3:
2428 case glslang::EOpConstructI64Vec4:
2429 case glslang::EOpConstructUint64:
2430 case glslang::EOpConstructU64Vec2:
2431 case glslang::EOpConstructU64Vec3:
2432 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002433 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002434 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002435 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002436 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002437 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002438 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002439 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002440 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002441 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002442 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002443 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002444 else if (node->getOp() == glslang::EOpConstructStruct ||
2445 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2446 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002447 std::vector<spv::Id> constituents;
2448 for (int c = 0; c < (int)arguments.size(); ++c)
2449 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002450 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002451 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002452 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002453 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002454 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002455
2456 builder.clearAccessChain();
2457 builder.setAccessChainRValue(constructed);
2458
2459 return false;
2460 }
2461
2462 // These six are component-wise compares with component-wise results.
2463 // Forward on to createBinaryOperation(), requesting a vector result.
2464 case glslang::EOpLessThan:
2465 case glslang::EOpGreaterThan:
2466 case glslang::EOpLessThanEqual:
2467 case glslang::EOpGreaterThanEqual:
2468 case glslang::EOpVectorEqual:
2469 case glslang::EOpVectorNotEqual:
2470 {
2471 // Map the operation to a binary
2472 binOp = node->getOp();
2473 reduceComparison = false;
2474 switch (node->getOp()) {
2475 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2476 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2477 default: binOp = node->getOp(); break;
2478 }
2479
2480 break;
2481 }
2482 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002483 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002484 binOp = glslang::EOpMul;
2485 break;
2486 case glslang::EOpOuterProduct:
2487 // two vectors multiplied to make a matrix
2488 binOp = glslang::EOpOuterProduct;
2489 break;
2490 case glslang::EOpDot:
2491 {
qining25262b32016-05-06 17:25:16 -04002492 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002493 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002494 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002495 binOp = glslang::EOpMul;
2496 break;
2497 }
2498 case glslang::EOpMod:
2499 // when an aggregate, this is the floating-point mod built-in function,
2500 // which can be emitted by the one in createBinaryOperation()
2501 binOp = glslang::EOpMod;
2502 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002503 case glslang::EOpEmitVertex:
2504 case glslang::EOpEndPrimitive:
2505 case glslang::EOpBarrier:
2506 case glslang::EOpMemoryBarrier:
2507 case glslang::EOpMemoryBarrierAtomicCounter:
2508 case glslang::EOpMemoryBarrierBuffer:
2509 case glslang::EOpMemoryBarrierImage:
2510 case glslang::EOpMemoryBarrierShared:
2511 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002512 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002513 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002514 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002515 case glslang::EOpWorkgroupMemoryBarrier:
2516 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002517 case glslang::EOpSubgroupBarrier:
2518 case glslang::EOpSubgroupMemoryBarrier:
2519 case glslang::EOpSubgroupMemoryBarrierBuffer:
2520 case glslang::EOpSubgroupMemoryBarrierImage:
2521 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002522 noReturnValue = true;
2523 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2524 break;
2525
Jeff Bolz36831c92018-09-05 10:11:41 -05002526 case glslang::EOpAtomicStore:
2527 noReturnValue = true;
2528 // fallthrough
2529 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002530 case glslang::EOpAtomicAdd:
2531 case glslang::EOpAtomicMin:
2532 case glslang::EOpAtomicMax:
2533 case glslang::EOpAtomicAnd:
2534 case glslang::EOpAtomicOr:
2535 case glslang::EOpAtomicXor:
2536 case glslang::EOpAtomicExchange:
2537 case glslang::EOpAtomicCompSwap:
2538 atomic = true;
2539 break;
2540
John Kessenich0d0c6d32017-07-23 16:08:26 -06002541 case glslang::EOpAtomicCounterAdd:
2542 case glslang::EOpAtomicCounterSubtract:
2543 case glslang::EOpAtomicCounterMin:
2544 case glslang::EOpAtomicCounterMax:
2545 case glslang::EOpAtomicCounterAnd:
2546 case glslang::EOpAtomicCounterOr:
2547 case glslang::EOpAtomicCounterXor:
2548 case glslang::EOpAtomicCounterExchange:
2549 case glslang::EOpAtomicCounterCompSwap:
2550 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2551 builder.addCapability(spv::CapabilityAtomicStorageOps);
2552 atomic = true;
2553 break;
2554
Chao Chen3c366992018-09-19 11:41:59 -07002555#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002556 case glslang::EOpIgnoreIntersectionNV:
2557 case glslang::EOpTerminateRayNV:
2558 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002559 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002560 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2561 noReturnValue = true;
2562 break;
2563#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002564 case glslang::EOpCooperativeMatrixLoad:
2565 case glslang::EOpCooperativeMatrixStore:
2566 noReturnValue = true;
2567 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002568 case glslang::EOpBeginInvocationInterlock:
2569 case glslang::EOpEndInvocationInterlock:
2570 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2571 noReturnValue = true;
2572 break;
Chao Chen3c366992018-09-19 11:41:59 -07002573
John Kessenich140f3df2015-06-26 16:58:36 -06002574 default:
2575 break;
2576 }
2577
2578 //
2579 // See if it maps to a regular operation.
2580 //
John Kessenich140f3df2015-06-26 16:58:36 -06002581 if (binOp != glslang::EOpNull) {
2582 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2583 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2584 assert(left && right);
2585
2586 builder.clearAccessChain();
2587 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002588 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002589
2590 builder.clearAccessChain();
2591 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002592 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002593
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002594 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002595 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002596 TranslateNoContractionDecoration(node->getType().getQualifier()),
2597 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002598 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002599 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002600 left->getType().getBasicType(), reduceComparison);
2601
2602 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002603 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002604 builder.clearAccessChain();
2605 builder.setAccessChainRValue(result);
2606
2607 return false;
2608 }
2609
John Kessenich426394d2015-07-23 10:22:48 -06002610 //
2611 // Create the list of operands.
2612 //
John Kessenich140f3df2015-06-26 16:58:36 -06002613 glslang::TIntermSequence& glslangOperands = node->getSequence();
2614 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002615 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002616 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002617 // special case l-value operands; there are just a few
2618 bool lvalue = false;
2619 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002620 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002621 case glslang::EOpModf:
2622 if (arg == 1)
2623 lvalue = true;
2624 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002625 case glslang::EOpInterpolateAtSample:
2626 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002627#ifdef AMD_EXTENSIONS
2628 case glslang::EOpInterpolateAtVertex:
2629#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002630 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002631 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002632
2633 // Does it need a swizzle inversion? If so, evaluation is inverted;
2634 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002635 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002636 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2637 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2638 }
Rex Xu7a26c172015-12-08 17:12:09 +08002639 break;
Rex Xud4782c12015-09-06 16:30:11 +08002640 case glslang::EOpAtomicAdd:
2641 case glslang::EOpAtomicMin:
2642 case glslang::EOpAtomicMax:
2643 case glslang::EOpAtomicAnd:
2644 case glslang::EOpAtomicOr:
2645 case glslang::EOpAtomicXor:
2646 case glslang::EOpAtomicExchange:
2647 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002648 case glslang::EOpAtomicLoad:
2649 case glslang::EOpAtomicStore:
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:
Rex Xud4782c12015-09-06 16:30:11 +08002659 if (arg == 0)
2660 lvalue = true;
2661 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002662 case glslang::EOpAddCarry:
2663 case glslang::EOpSubBorrow:
2664 if (arg == 2)
2665 lvalue = true;
2666 break;
2667 case glslang::EOpUMulExtended:
2668 case glslang::EOpIMulExtended:
2669 if (arg >= 2)
2670 lvalue = true;
2671 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002672 case glslang::EOpCooperativeMatrixLoad:
2673 if (arg == 0 || arg == 1)
2674 lvalue = true;
2675 break;
2676 case glslang::EOpCooperativeMatrixStore:
2677 if (arg == 1)
2678 lvalue = true;
2679 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002680 default:
2681 break;
2682 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002683 builder.clearAccessChain();
2684 if (invertedType != spv::NoType && arg == 0)
2685 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2686 else
2687 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002688
2689 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2690 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2691
2692 if (arg == 1) {
2693 // fold "element" parameter into the access chain
2694 spv::Builder::AccessChain save = builder.getAccessChain();
2695 builder.clearAccessChain();
2696 glslangOperands[2]->traverse(this);
2697
2698 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2699
2700 builder.setAccessChain(save);
2701
2702 // Point to the first element of the array.
2703 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002704 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002705
2706 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2707 unsigned int alignment = builder.getAccessChain().alignment;
2708
2709 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2710 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2711 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2712 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2713 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2714 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2715 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2716 }
2717
2718 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2719
2720 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2721 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2722 }
2723
2724 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2725 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2726 }
2727 } else if (arg == 2) {
2728 continue;
2729 }
2730 }
2731
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002732 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002733 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002734 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2735 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2736 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002737 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002738 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002739 }
John Kessenich140f3df2015-06-26 16:58:36 -06002740 }
John Kessenich426394d2015-07-23 10:22:48 -06002741
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002742 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002743 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2744 std::vector<spv::IdImmediate> idImmOps;
2745
2746 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2747 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2748 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2749 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2750 // get the pointee type
2751 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2752 assert(builder.isCooperativeMatrixType(typeId));
2753 // do the op
2754 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2755 // store the result to the pointer (out param 'm')
2756 builder.createStore(result, operands[0]);
2757 result = 0;
2758 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2759 std::vector<spv::IdImmediate> idImmOps;
2760
2761 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2762 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2763 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2764 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2765 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2766
2767 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2768 result = 0;
2769 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002770 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002771 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002772 } else {
2773 // Pass through to generic operations.
2774 switch (glslangOperands.size()) {
2775 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002776 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002777 break;
2778 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002779 {
2780 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002781 TranslateNoContractionDecoration(node->getType().getQualifier()),
2782 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002783 result = createUnaryOperation(
2784 node->getOp(), decorations,
2785 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002786 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002787 }
John Kessenich426394d2015-07-23 10:22:48 -06002788 break;
2789 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002790 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002791 break;
2792 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002793 if (invertedType)
2794 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002795 }
2796
2797 if (noReturnValue)
2798 return false;
2799
2800 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002801 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002802 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002803 } else {
2804 builder.clearAccessChain();
2805 builder.setAccessChainRValue(result);
2806 return false;
2807 }
2808}
2809
John Kessenich433e9ff2017-01-26 20:31:11 -07002810// This path handles both if-then-else and ?:
2811// The if-then-else has a node type of void, while
2812// ?: has either a void or a non-void node type
2813//
2814// Leaving the result, when not void:
2815// GLSL only has r-values as the result of a :?, but
2816// if we have an l-value, that can be more efficient if it will
2817// become the base of a complex r-value expression, because the
2818// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002819bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2820{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002821 // see if OpSelect can handle it
2822 const auto isOpSelectable = [&]() {
2823 if (node->getBasicType() == glslang::EbtVoid)
2824 return false;
2825 // OpSelect can do all other types starting with SPV 1.4
2826 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2827 // pre-1.4, only scalars and vectors can be handled
2828 if ((!node->getType().isScalar() && !node->getType().isVector()))
2829 return false;
2830 }
2831 return true;
2832 };
2833
John Kessenich4bee5312018-02-20 21:29:05 -07002834 // See if it simple and safe, or required, to execute both sides.
2835 // Crucially, side effects must be either semantically required or avoided,
2836 // and there are performance trade-offs.
2837 // Return true if required or a good idea (and safe) to execute both sides,
2838 // false otherwise.
2839 const auto bothSidesPolicy = [&]() -> bool {
2840 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002841 if (node->getTrueBlock() == nullptr ||
2842 node->getFalseBlock() == nullptr)
2843 return false;
2844
John Kessenich4bee5312018-02-20 21:29:05 -07002845 // required? (unless we write additional code to look for side effects
2846 // and make performance trade-offs if none are present)
2847 if (!node->getShortCircuit())
2848 return true;
2849
2850 // if not required to execute both, decide based on performance/practicality...
2851
John Kessenich0c1e71a2019-01-10 18:23:06 +07002852 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002853 return false;
2854
John Kessenich433e9ff2017-01-26 20:31:11 -07002855 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2856 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2857
2858 // return true if a single operand to ? : is okay for OpSelect
2859 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002860 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002861 };
2862
2863 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2864 operandOkay(node->getFalseBlock()->getAsTyped());
2865 };
2866
John Kessenich4bee5312018-02-20 21:29:05 -07002867 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2868 // emit the condition before doing anything with selection
2869 node->getCondition()->traverse(this);
2870 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2871
2872 // Find a way of executing both sides and selecting the right result.
2873 const auto executeBothSides = [&]() -> void {
2874 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002875 node->getTrueBlock()->traverse(this);
2876 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2877 node->getFalseBlock()->traverse(this);
2878 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2879
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002880 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002881
John Kessenich4bee5312018-02-20 21:29:05 -07002882 // done if void
2883 if (node->getBasicType() == glslang::EbtVoid)
2884 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002885
John Kessenich4bee5312018-02-20 21:29:05 -07002886 // emit code to select between trueValue and falseValue
2887
2888 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002889 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002890 // Emit OpSelect for this selection.
2891
2892 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002893 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2894 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002895 condition = builder.smearScalar(spv::NoPrecision, condition,
2896 builder.makeVectorType(builder.makeBoolType(),
2897 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002898 }
John Kessenich4bee5312018-02-20 21:29:05 -07002899
2900 // OpSelect
2901 result = builder.createTriOp(spv::OpSelect,
2902 convertGlslangToSpvType(node->getType()), condition,
2903 trueValue, falseValue);
2904
2905 builder.clearAccessChain();
2906 builder.setAccessChainRValue(result);
2907 } else {
2908 // We need control flow to select the result.
2909 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2910 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2911
2912 // Selection control:
2913 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2914
2915 // make an "if" based on the value created by the condition
2916 spv::Builder::If ifBuilder(condition, control, builder);
2917
2918 // emit the "then" statement
2919 builder.createStore(trueValue, result);
2920 ifBuilder.makeBeginElse();
2921 // emit the "else" statement
2922 builder.createStore(falseValue, result);
2923
2924 // finish off the control flow
2925 ifBuilder.makeEndIf();
2926
2927 builder.clearAccessChain();
2928 builder.setAccessChainLValue(result);
2929 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002930 };
2931
John Kessenich4bee5312018-02-20 21:29:05 -07002932 // Execute the one side needed, as per the condition
2933 const auto executeOneSide = [&]() {
2934 // Always emit control flow.
2935 if (node->getBasicType() != glslang::EbtVoid)
2936 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002937
John Kessenich4bee5312018-02-20 21:29:05 -07002938 // Selection control:
2939 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2940
2941 // make an "if" based on the value created by the condition
2942 spv::Builder::If ifBuilder(condition, control, builder);
2943
2944 // emit the "then" statement
2945 if (node->getTrueBlock() != nullptr) {
2946 node->getTrueBlock()->traverse(this);
2947 if (result != spv::NoResult)
2948 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2949 }
2950
2951 if (node->getFalseBlock() != nullptr) {
2952 ifBuilder.makeBeginElse();
2953 // emit the "else" statement
2954 node->getFalseBlock()->traverse(this);
2955 if (result != spv::NoResult)
2956 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2957 }
2958
2959 // finish off the control flow
2960 ifBuilder.makeEndIf();
2961
2962 if (result != spv::NoResult) {
2963 builder.clearAccessChain();
2964 builder.setAccessChainLValue(result);
2965 }
2966 };
2967
2968 // Try for OpSelect (or a requirement to execute both sides)
2969 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002970 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2971 if (node->getType().getQualifier().isSpecConstant())
2972 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002973 executeBothSides();
2974 } else
2975 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002976
2977 return false;
2978}
2979
2980bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2981{
2982 // emit and get the condition before doing anything with switch
2983 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002984 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002985
Rex Xu57e65922017-07-04 23:23:40 +08002986 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002987 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002988
John Kessenich140f3df2015-06-26 16:58:36 -06002989 // browse the children to sort out code segments
2990 int defaultSegment = -1;
2991 std::vector<TIntermNode*> codeSegments;
2992 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2993 std::vector<int> caseValues;
2994 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2995 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2996 TIntermNode* child = *c;
2997 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002998 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002999 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003000 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003001 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3002 } else
3003 codeSegments.push_back(child);
3004 }
3005
qining25262b32016-05-06 17:25:16 -04003006 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003007 // statements between the last case and the end of the switch statement
3008 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3009 (int)codeSegments.size() == defaultSegment)
3010 codeSegments.push_back(nullptr);
3011
3012 // make the switch statement
3013 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003014 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003015
3016 // emit all the code in the segments
3017 breakForLoop.push(false);
3018 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3019 builder.nextSwitchSegment(segmentBlocks, s);
3020 if (codeSegments[s])
3021 codeSegments[s]->traverse(this);
3022 else
3023 builder.addSwitchBreak();
3024 }
3025 breakForLoop.pop();
3026
3027 builder.endSwitch(segmentBlocks);
3028
3029 return false;
3030}
3031
3032void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3033{
3034 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003035 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003036
3037 builder.clearAccessChain();
3038 builder.setAccessChainRValue(constant);
3039}
3040
3041bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3042{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003043 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003044 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003045
3046 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003047 std::vector<unsigned int> operands;
3048 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003049
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003050 // Spec requires back edges to target header blocks, and every header block
3051 // must dominate its merge block. Make a header block first to ensure these
3052 // conditions are met. By definition, it will contain OpLoopMerge, followed
3053 // by a block-ending branch. But we don't want to put any other body/test
3054 // instructions in it, since the body/test may have arbitrary instructions,
3055 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003056 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003057 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003058 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003059 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003060 spv::Block& test = builder.makeNewBlock();
3061 builder.createBranch(&test);
3062
3063 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003064 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003065 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003066 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3067
3068 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003069 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003070 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003071 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003072 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003073 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003074
3075 builder.setBuildPoint(&blocks.continue_target);
3076 if (node->getTerminal())
3077 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003078 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003079 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003080 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003081 builder.createBranch(&blocks.body);
3082
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003083 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003084 builder.setBuildPoint(&blocks.body);
3085 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003086 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003087 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003088 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003089
3090 builder.setBuildPoint(&blocks.continue_target);
3091 if (node->getTerminal())
3092 node->getTerminal()->traverse(this);
3093 if (node->getTest()) {
3094 node->getTest()->traverse(this);
3095 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003096 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003097 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003098 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003099 // TODO: unless there was a break/return/discard instruction
3100 // somewhere in the body, this is an infinite loop, so we should
3101 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003102 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003103 }
John Kessenich140f3df2015-06-26 16:58:36 -06003104 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003105 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003106 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003107 return false;
3108}
3109
3110bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3111{
3112 if (node->getExpression())
3113 node->getExpression()->traverse(this);
3114
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003115 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003116
John Kessenich140f3df2015-06-26 16:58:36 -06003117 switch (node->getFlowOp()) {
3118 case glslang::EOpKill:
3119 builder.makeDiscard();
3120 break;
3121 case glslang::EOpBreak:
3122 if (breakForLoop.top())
3123 builder.createLoopExit();
3124 else
3125 builder.addSwitchBreak();
3126 break;
3127 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003128 builder.createLoopContinue();
3129 break;
3130 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003131 if (node->getExpression()) {
3132 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3133 spv::Id returnId = accessChainLoad(glslangReturnType);
3134 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3135 builder.clearAccessChain();
3136 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3137 builder.setAccessChainLValue(copyId);
3138 multiTypeStore(glslangReturnType, returnId);
3139 returnId = builder.createLoad(copyId);
3140 }
3141 builder.makeReturn(false, returnId);
3142 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003143 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003144
3145 builder.clearAccessChain();
3146 break;
3147
Jeff Bolzba6170b2019-07-01 09:23:23 -05003148 case glslang::EOpDemote:
3149 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3150 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3151 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3152 break;
3153
John Kessenich140f3df2015-06-26 16:58:36 -06003154 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003155 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157 }
3158
3159 return false;
3160}
3161
John Kessenich9c14f772019-06-17 08:38:35 -06003162spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003163{
qining25262b32016-05-06 17:25:16 -04003164 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003165 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003166 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003167 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003168 spv::Id result = createSpvConstant(*node);
3169 if (result != spv::NoResult)
3170 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003171 }
3172
3173 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003174 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003175 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3176 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003177
Rex Xucabbb782017-03-24 13:41:14 +08003178 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3179 node->getType().containsBasicType(glslang::EbtInt16) ||
3180 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003181 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003182 switch (storageClass) {
3183 case spv::StorageClassInput:
3184 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003185 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003186 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003187 break;
3188 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003189 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003190 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003191 break;
3192 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003193 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003194 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3195 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003196 else
3197 builder.addCapability(spv::CapabilityStorageUniform16);
3198 break;
3199 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003200 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003201 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3202 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3203 break;
3204 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003205 if (node->getType().containsBasicType(glslang::EbtFloat16))
3206 builder.addCapability(spv::CapabilityFloat16);
3207 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3208 node->getType().containsBasicType(glslang::EbtUint16))
3209 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003210 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003211 }
3212 }
Rex Xuf89ad982017-04-07 23:22:33 +08003213
John Kessenich312dcfb2018-07-03 13:19:51 -06003214 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3215 node->getType().containsBasicType(glslang::EbtUint8);
3216 if (contains8BitType) {
3217 if (storageClass == spv::StorageClassPushConstant) {
3218 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3219 builder.addCapability(spv::CapabilityStoragePushConstant8);
3220 } else if (storageClass == spv::StorageClassUniform) {
3221 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3222 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003223 } else if (storageClass == spv::StorageClassStorageBuffer) {
3224 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3225 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003226 } else {
3227 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003228 }
3229 }
3230
John Kessenich140f3df2015-06-26 16:58:36 -06003231 const char* name = node->getName().c_str();
3232 if (glslang::IsAnonymous(name))
3233 name = "";
3234
3235 return builder.createVariable(storageClass, spvType, name);
3236}
3237
3238// Return type Id of the sampled type.
3239spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3240{
3241 switch (sampler.type) {
3242 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003243#ifdef AMD_EXTENSIONS
3244 case glslang::EbtFloat16:
3245 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3246 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3247 return builder.makeFloatType(16);
3248#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003249 case glslang::EbtInt: return builder.makeIntType(32);
3250 case glslang::EbtUint: return builder.makeUintType(32);
3251 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003252 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003253 return builder.makeFloatType(32);
3254 }
3255}
3256
John Kessenich8c8505c2016-07-26 12:50:38 -06003257// If node is a swizzle operation, return the type that should be used if
3258// the swizzle base is first consumed by another operation, before the swizzle
3259// is applied.
3260spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3261{
John Kessenichecba76f2017-01-06 00:34:48 -07003262 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003263 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3264 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3265 else
3266 return spv::NoType;
3267}
3268
3269// When inverting a swizzle with a parent op, this function
3270// will apply the swizzle operation to a completed parent operation.
3271spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3272{
3273 std::vector<unsigned> swizzle;
3274 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3275 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3276}
3277
John Kessenich8c8505c2016-07-26 12:50:38 -06003278// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3279void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3280{
3281 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3282 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3283 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3284}
3285
John Kessenich3ac051e2015-12-20 11:29:16 -07003286// Convert from a glslang type to an SPV type, by calling into a
3287// recursive version of this function. This establishes the inherited
3288// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003289spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003290{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003291 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003292}
3293
3294// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003295// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003296// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003297spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003298 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3299 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003300{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003301 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003302
3303 switch (type.getBasicType()) {
3304 case glslang::EbtVoid:
3305 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003306 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003307 break;
3308 case glslang::EbtFloat:
3309 spvType = builder.makeFloatType(32);
3310 break;
3311 case glslang::EbtDouble:
3312 spvType = builder.makeFloatType(64);
3313 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003314 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003315 spvType = builder.makeFloatType(16);
3316 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003317 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003318 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3319 // a 32-bit int where non-0 means true.
3320 if (explicitLayout != glslang::ElpNone)
3321 spvType = builder.makeUintType(32);
3322 else
3323 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003324 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003325 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003326 spvType = builder.makeIntType(8);
3327 break;
3328 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003329 spvType = builder.makeUintType(8);
3330 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003331 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003332 spvType = builder.makeIntType(16);
3333 break;
3334 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003335 spvType = builder.makeUintType(16);
3336 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003337 case glslang::EbtInt:
3338 spvType = builder.makeIntType(32);
3339 break;
3340 case glslang::EbtUint:
3341 spvType = builder.makeUintType(32);
3342 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003343 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003344 spvType = builder.makeIntType(64);
3345 break;
3346 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003347 spvType = builder.makeUintType(64);
3348 break;
John Kessenich426394d2015-07-23 10:22:48 -06003349 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003350 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003351 spvType = builder.makeUintType(32);
3352 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003353#ifdef NV_EXTENSIONS
3354 case glslang::EbtAccStructNV:
3355 spvType = builder.makeAccelerationStructureNVType();
3356 break;
3357#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003358 case glslang::EbtSampler:
3359 {
3360 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003361 if (sampler.sampler) {
3362 // pure sampler
3363 spvType = builder.makeSamplerType();
3364 } else {
3365 // an image is present, make its type
3366 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3367 sampler.image ? 2 : 1, TranslateImageFormat(type));
3368 if (sampler.combined) {
3369 // already has both image and sampler, make the combined type
3370 spvType = builder.makeSampledImageType(spvType);
3371 }
John Kessenich55e7d112015-11-15 21:33:39 -07003372 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003373 }
John Kessenich140f3df2015-06-26 16:58:36 -06003374 break;
3375 case glslang::EbtStruct:
3376 case glslang::EbtBlock:
3377 {
3378 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003379 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003380
3381 // Try to share structs for different layouts, but not yet for other
3382 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003383 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003384 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003385 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003386 break;
3387
3388 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003389 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003390 memberRemapper[glslangMembers].resize(glslangMembers->size());
3391 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003392 }
3393 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003394 case glslang::EbtReference:
3395 {
3396 // Make the forward pointer, then recurse to convert the structure type, then
3397 // patch up the forward pointer with a real pointer type.
3398 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3399 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3400 forwardPointers[type.getReferentType()] = forwardId;
3401 }
3402 spvType = forwardPointers[type.getReferentType()];
3403 if (!forwardReferenceOnly) {
3404 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3405 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3406 forwardPointers[type.getReferentType()],
3407 referentType);
3408 }
3409 }
3410 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003411 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003412 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003413 break;
3414 }
3415
3416 if (type.isMatrix())
3417 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3418 else {
3419 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3420 if (type.getVectorSize() > 1)
3421 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3422 }
3423
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003424 if (type.isCoopMat()) {
3425 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3426 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3427 if (type.getBasicType() == glslang::EbtFloat16)
3428 builder.addCapability(spv::CapabilityFloat16);
3429
3430 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3431 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3432 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3433
3434 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3435 }
3436
John Kessenich140f3df2015-06-26 16:58:36 -06003437 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003438 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3439
John Kessenichc9a80832015-09-12 12:17:44 -06003440 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003441 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003442 // We need to decorate array strides for types needing explicit layout, except blocks.
3443 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003444 // Use a dummy glslang type for querying internal strides of
3445 // arrays of arrays, but using just a one-dimensional array.
3446 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003447 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3448 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003449
3450 // Will compute the higher-order strides here, rather than making a whole
3451 // pile of types and doing repetitive recursion on their contents.
3452 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3453 }
John Kessenichf8842e52016-01-04 19:22:56 -07003454
3455 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003456 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003457 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003458 if (stride > 0)
3459 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003460 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003461 }
3462 } else {
3463 // single-dimensional array, and don't yet have stride
3464
John Kessenichf8842e52016-01-04 19:22:56 -07003465 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003466 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3467 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003468 }
John Kessenich31ed4832015-09-09 17:51:38 -06003469
John Kessenichead86222018-03-28 18:01:20 -06003470 // Do the outer dimension, which might not be known for a runtime-sized array.
3471 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3472 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003473 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003474 else {
3475 if (!lastBufferBlockMember) {
3476 builder.addExtension("SPV_EXT_descriptor_indexing");
3477 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3478 }
John Kessenichead86222018-03-28 18:01:20 -06003479 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003480 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003481 if (stride > 0)
3482 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003483 }
3484
3485 return spvType;
3486}
3487
John Kessenich0e737842017-03-24 18:38:16 -06003488// TODO: this functionality should exist at a higher level, in creating the AST
3489//
3490// Identify interface members that don't have their required extension turned on.
3491//
3492bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3493{
Chao Chen3c366992018-09-19 11:41:59 -07003494#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003495 auto& extensions = glslangIntermediate->getRequestedExtensions();
3496
Rex Xubcf291a2017-03-29 23:01:36 +08003497 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3498 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3499 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003500 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3501 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3502 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003503
3504 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3505 if (member.getFieldName() == "gl_ViewportMask" &&
3506 extensions.find("GL_NV_viewport_array2") == extensions.end())
3507 return true;
3508 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3509 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3510 return true;
3511 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3512 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3513 return true;
3514 }
3515#endif
John Kessenich0e737842017-03-24 18:38:16 -06003516
3517 return false;
3518};
3519
John Kessenich6090df02016-06-30 21:18:02 -06003520// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3521// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3522// Mutually recursive with convertGlslangToSpvType().
3523spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3524 const glslang::TTypeList* glslangMembers,
3525 glslang::TLayoutPacking explicitLayout,
3526 const glslang::TQualifier& qualifier)
3527{
3528 // Create a vector of struct types for SPIR-V to consume
3529 std::vector<spv::Id> spvMembers;
3530 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003531 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003532 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3533 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3534 if (glslangMember.hiddenMember()) {
3535 ++memberDelta;
3536 if (type.getBasicType() == glslang::EbtBlock)
3537 memberRemapper[glslangMembers][i] = -1;
3538 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003539 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003540 if (filterMember(glslangMember)) {
3541 memberDelta++;
3542 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003543 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003544 }
3545 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003546 }
John Kessenich6090df02016-06-30 21:18:02 -06003547 // modify just this child's view of the qualifier
3548 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3549 InheritQualifiers(memberQualifier, qualifier);
3550
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003551 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003552 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003553 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003554
3555 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003556 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3557 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003558
3559 // Make forward pointers for any pointer members, and create a list of members to
3560 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003561 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003562 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3563 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3564 }
3565 spvMembers.push_back(
3566 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3567 } else {
3568 spvMembers.push_back(
3569 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3570 }
John Kessenich6090df02016-06-30 21:18:02 -06003571 }
3572 }
3573
3574 // Make the SPIR-V type
3575 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003576 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003577 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3578
3579 // Decorate it
3580 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3581
John Kessenichd72f4882019-01-16 14:55:37 +07003582 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003583 auto it = deferredForwardPointers[i];
3584 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3585 }
3586
John Kessenich6090df02016-06-30 21:18:02 -06003587 return spvType;
3588}
3589
3590void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3591 const glslang::TTypeList* glslangMembers,
3592 glslang::TLayoutPacking explicitLayout,
3593 const glslang::TQualifier& qualifier,
3594 spv::Id spvType)
3595{
3596 // Name and decorate the non-hidden members
3597 int offset = -1;
3598 int locationOffset = 0; // for use within the members of this struct
3599 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3600 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3601 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003602 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003603 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003604 if (filterMember(glslangMember))
3605 continue;
3606 }
John Kessenich6090df02016-06-30 21:18:02 -06003607
3608 // modify just this child's view of the qualifier
3609 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3610 InheritQualifiers(memberQualifier, qualifier);
3611
3612 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003613 if (member < 0)
3614 continue;
3615
3616 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3617 builder.addMemberDecoration(spvType, member,
3618 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3619 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3620 // Add interpolation and auxiliary storage decorations only to
3621 // top-level members of Input and Output storage classes
3622 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3623 type.getQualifier().storage == glslang::EvqVaryingOut) {
3624 if (type.getBasicType() == glslang::EbtBlock ||
3625 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3626 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3627 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003628#ifdef NV_EXTENSIONS
3629 addMeshNVDecoration(spvType, member, memberQualifier);
3630#endif
John Kessenich6090df02016-06-30 21:18:02 -06003631 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003632 }
3633 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003634
John Kessenich5d610ee2018-03-07 18:05:55 -07003635 if (type.getBasicType() == glslang::EbtBlock &&
3636 qualifier.storage == glslang::EvqBuffer) {
3637 // Add memory decorations only to top-level members of shader storage block
3638 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003639 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003640 for (unsigned int i = 0; i < memory.size(); ++i)
3641 builder.addMemberDecoration(spvType, member, memory[i]);
3642 }
John Kessenich6090df02016-06-30 21:18:02 -06003643
John Kessenich5d610ee2018-03-07 18:05:55 -07003644 // Location assignment was already completed correctly by the front end,
3645 // just track whether a member needs to be decorated.
3646 // Ignore member locations if the container is an array, as that's
3647 // ill-specified and decisions have been made to not allow this.
3648 if (! type.isArray() && memberQualifier.hasLocation())
3649 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003650
John Kessenich5d610ee2018-03-07 18:05:55 -07003651 if (qualifier.hasLocation()) // track for upcoming inheritance
3652 locationOffset += glslangIntermediate->computeTypeLocationSize(
3653 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003654
John Kessenich5d610ee2018-03-07 18:05:55 -07003655 // component, XFB, others
3656 if (glslangMember.getQualifier().hasComponent())
3657 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3658 glslangMember.getQualifier().layoutComponent);
3659 if (glslangMember.getQualifier().hasXfbOffset())
3660 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3661 glslangMember.getQualifier().layoutXfbOffset);
3662 else if (explicitLayout != glslang::ElpNone) {
3663 // figure out what to do with offset, which is accumulating
3664 int nextOffset;
3665 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3666 if (offset >= 0)
3667 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3668 offset = nextOffset;
3669 }
John Kessenich6090df02016-06-30 21:18:02 -06003670
John Kessenich5d610ee2018-03-07 18:05:55 -07003671 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3672 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3673 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003674
John Kessenich5d610ee2018-03-07 18:05:55 -07003675 // built-in variable decorations
3676 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3677 if (builtIn != spv::BuiltInMax)
3678 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003679
John Kessenich5611c6d2018-04-05 11:25:02 -06003680 // nonuniform
3681 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3682
John Kessenichead86222018-03-28 18:01:20 -06003683 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3684 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3685 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3686 memberQualifier.semanticName);
3687 }
3688
chaoc771d89f2017-01-13 01:10:53 -08003689#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003690 if (builtIn == spv::BuiltInLayer) {
3691 // SPV_NV_viewport_array2 extension
3692 if (glslangMember.getQualifier().layoutViewportRelative){
3693 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3694 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3695 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003696 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003697 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3698 builder.addMemberDecoration(spvType, member,
3699 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3700 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3701 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3702 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003703 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003704 }
3705 if (glslangMember.getQualifier().layoutPassthrough) {
3706 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3707 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3708 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3709 }
chaoc771d89f2017-01-13 01:10:53 -08003710#endif
John Kessenich6090df02016-06-30 21:18:02 -06003711 }
3712
3713 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003714 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3715 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003716}
3717
John Kessenich6c292d32016-02-15 20:58:50 -07003718// Turn the expression forming the array size into an id.
3719// This is not quite trivial, because of specialization constants.
3720// Sometimes, a raw constant is turned into an Id, and sometimes
3721// a specialization constant expression is.
3722spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3723{
3724 // First, see if this is sized with a node, meaning a specialization constant:
3725 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3726 if (specNode != nullptr) {
3727 builder.clearAccessChain();
3728 specNode->traverse(this);
3729 return accessChainLoad(specNode->getAsTyped()->getType());
3730 }
qining25262b32016-05-06 17:25:16 -04003731
John Kessenich6c292d32016-02-15 20:58:50 -07003732 // Otherwise, need a compile-time (front end) size, get it:
3733 int size = arraySizes.getDimSize(dim);
3734 assert(size > 0);
3735 return builder.makeUintConstant(size);
3736}
3737
John Kessenich103bef92016-02-08 21:38:15 -07003738// Wrap the builder's accessChainLoad to:
3739// - localize handling of RelaxedPrecision
3740// - use the SPIR-V inferred type instead of another conversion of the glslang type
3741// (avoids unnecessary work and possible type punning for structures)
3742// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003743spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3744{
John Kessenich103bef92016-02-08 21:38:15 -07003745 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003746
3747 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3748 coherentFlags |= TranslateCoherent(type);
3749
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003750 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003751 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003752
John Kessenich5611c6d2018-04-05 11:25:02 -06003753 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003754 TranslateNonUniformDecoration(type.getQualifier()),
3755 nominalTypeId,
3756 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003757 TranslateMemoryScope(coherentFlags),
3758 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003759
3760 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003761 if (type.getBasicType() == glslang::EbtBool) {
3762 if (builder.isScalarType(nominalTypeId)) {
3763 // Conversion for bool
3764 spv::Id boolType = builder.makeBoolType();
3765 if (nominalTypeId != boolType)
3766 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3767 } else if (builder.isVectorType(nominalTypeId)) {
3768 // Conversion for bvec
3769 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3770 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3771 if (nominalTypeId != bvecType)
3772 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3773 }
3774 }
John Kessenich103bef92016-02-08 21:38:15 -07003775
3776 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003777}
3778
Rex Xu27253232016-02-23 17:51:09 +08003779// Wrap the builder's accessChainStore to:
3780// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003781//
3782// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003783void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3784{
3785 // Need to convert to abstract types when necessary
3786 if (type.getBasicType() == glslang::EbtBool) {
3787 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3788
3789 if (builder.isScalarType(nominalTypeId)) {
3790 // Conversion for bool
3791 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003792 if (nominalTypeId != boolType) {
3793 // keep these outside arguments, for determinant order-of-evaluation
3794 spv::Id one = builder.makeUintConstant(1);
3795 spv::Id zero = builder.makeUintConstant(0);
3796 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3797 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003798 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003799 } else if (builder.isVectorType(nominalTypeId)) {
3800 // Conversion for bvec
3801 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3802 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003803 if (nominalTypeId != bvecType) {
3804 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003805 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3806 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3807 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003808 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003809 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3810 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003811 }
3812 }
3813
Jeff Bolz36831c92018-09-05 10:11:41 -05003814 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3815 coherentFlags |= TranslateCoherent(type);
3816
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003817 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003818 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003819
Jeff Bolz36831c92018-09-05 10:11:41 -05003820 builder.accessChainStore(rvalue,
3821 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003822 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003823}
3824
John Kessenich4bf71552016-09-02 11:20:21 -06003825// For storing when types match at the glslang level, but not might match at the
3826// SPIR-V level.
3827//
3828// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003829// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003830// as in a member-decorated way.
3831//
3832// NOTE: This function can handle any store request; if it's not special it
3833// simplifies to a simple OpStore.
3834//
3835// Implicitly uses the existing builder.accessChain as the storage target.
3836void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3837{
John Kessenichb3e24e42016-09-11 12:33:43 -06003838 // we only do the complex path here if it's an aggregate
3839 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003840 accessChainStore(type, rValue);
3841 return;
3842 }
3843
John Kessenichb3e24e42016-09-11 12:33:43 -06003844 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003845 spv::Id rType = builder.getTypeId(rValue);
3846 spv::Id lValue = builder.accessChainGetLValue();
3847 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3848 if (lType == rType) {
3849 accessChainStore(type, rValue);
3850 return;
3851 }
3852
John Kessenichb3e24e42016-09-11 12:33:43 -06003853 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003854 // where the two types were the same type in GLSL. This requires member
3855 // by member copy, recursively.
3856
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003857 // SPIR-V 1.4 added an instruction to do help do this.
3858 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3859 // However, bool in uniform space is changed to int, so
3860 // OpCopyLogical does not work for that.
3861 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3862 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3863 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3864 if (lBool == rBool) {
3865 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3866 accessChainStore(type, logicalCopy);
3867 return;
3868 }
3869 }
3870
John Kessenichb3e24e42016-09-11 12:33:43 -06003871 // If an array, copy element by element.
3872 if (type.isArray()) {
3873 glslang::TType glslangElementType(type, 0);
3874 spv::Id elementRType = builder.getContainedTypeId(rType);
3875 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3876 // get the source member
3877 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003878
John Kessenichb3e24e42016-09-11 12:33:43 -06003879 // set up the target storage
3880 builder.clearAccessChain();
3881 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003882 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003883
John Kessenichb3e24e42016-09-11 12:33:43 -06003884 // store the member
3885 multiTypeStore(glslangElementType, elementRValue);
3886 }
3887 } else {
3888 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003889
John Kessenichb3e24e42016-09-11 12:33:43 -06003890 // loop over structure members
3891 const glslang::TTypeList& members = *type.getStruct();
3892 for (int m = 0; m < (int)members.size(); ++m) {
3893 const glslang::TType& glslangMemberType = *members[m].type;
3894
3895 // get the source member
3896 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3897 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3898
3899 // set up the target storage
3900 builder.clearAccessChain();
3901 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003902 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003903
3904 // store the member
3905 multiTypeStore(glslangMemberType, memberRValue);
3906 }
John Kessenich4bf71552016-09-02 11:20:21 -06003907 }
3908}
3909
John Kessenichf85e8062015-12-19 13:57:10 -07003910// Decide whether or not this type should be
3911// decorated with offsets and strides, and if so
3912// whether std140 or std430 rules should be applied.
3913glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003914{
John Kessenichf85e8062015-12-19 13:57:10 -07003915 // has to be a block
3916 if (type.getBasicType() != glslang::EbtBlock)
3917 return glslang::ElpNone;
3918
Chao Chen3c366992018-09-19 11:41:59 -07003919 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003920 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003921 type.getQualifier().storage != glslang::EvqBuffer &&
3922 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003923 return glslang::ElpNone;
3924
3925 // return the layout to use
3926 switch (type.getQualifier().layoutPacking) {
3927 case glslang::ElpStd140:
3928 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003929 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003930 return type.getQualifier().layoutPacking;
3931 default:
3932 return glslang::ElpNone;
3933 }
John Kessenich31ed4832015-09-09 17:51:38 -06003934}
3935
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003936// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003937int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003938{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003939 int size;
John Kessenich49987892015-12-29 17:11:44 -07003940 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003941 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003942
3943 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003944}
3945
John Kessenich49987892015-12-29 17:11:44 -07003946// 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 -07003947// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003948int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003949{
John Kessenich49987892015-12-29 17:11:44 -07003950 glslang::TType elementType;
3951 elementType.shallowCopy(matrixType);
3952 elementType.clearArraySizes();
3953
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003954 int size;
John Kessenich49987892015-12-29 17:11:44 -07003955 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003956 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003957
3958 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003959}
3960
John Kessenich5e4b1242015-08-06 22:53:06 -06003961// Given a member type of a struct, realign the current offset for it, and compute
3962// the next (not yet aligned) offset for the next member, which will get aligned
3963// on the next call.
3964// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3965// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3966// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003967void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003968 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003969{
3970 // this will get a positive value when deemed necessary
3971 nextOffset = -1;
3972
John Kessenich5e4b1242015-08-06 22:53:06 -06003973 // override anything in currentOffset with user-set offset
3974 if (memberType.getQualifier().hasOffset())
3975 currentOffset = memberType.getQualifier().layoutOffset;
3976
3977 // It could be that current linker usage in glslang updated all the layoutOffset,
3978 // in which case the following code does not matter. But, that's not quite right
3979 // once cross-compilation unit GLSL validation is done, as the original user
3980 // settings are needed in layoutOffset, and then the following will come into play.
3981
John Kessenichf85e8062015-12-19 13:57:10 -07003982 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003983 if (! memberType.getQualifier().hasOffset())
3984 currentOffset = -1;
3985
3986 return;
3987 }
3988
John Kessenichf85e8062015-12-19 13:57:10 -07003989 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003990 if (currentOffset < 0)
3991 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003992
John Kessenich5e4b1242015-08-06 22:53:06 -06003993 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3994 // but possibly not yet correctly aligned.
3995
3996 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003997 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003998 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003999
4000 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004001 // TODO: make this consistent in early phases of code:
4002 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4003 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4004 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004005 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004006 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004007 int dummySize;
4008 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4009 if (componentAlignment <= 4)
4010 memberAlignment = componentAlignment;
4011 }
4012
4013 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004015
4016 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004017 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004018 glslang::RoundToPow2(currentOffset, 16);
4019
John Kessenich5e4b1242015-08-06 22:53:06 -06004020 nextOffset = currentOffset + memberSize;
4021}
4022
David Netoa901ffe2016-06-08 14:11:40 +01004023void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004024{
David Netoa901ffe2016-06-08 14:11:40 +01004025 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4026 switch (glslangBuiltIn)
4027 {
4028 case glslang::EbvClipDistance:
4029 case glslang::EbvCullDistance:
4030 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08004031#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08004032 case glslang::EbvViewportMaskNV:
4033 case glslang::EbvSecondaryPositionNV:
4034 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004035 case glslang::EbvPositionPerViewNV:
4036 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004037 case glslang::EbvTaskCountNV:
4038 case glslang::EbvPrimitiveCountNV:
4039 case glslang::EbvPrimitiveIndicesNV:
4040 case glslang::EbvClipDistancePerViewNV:
4041 case glslang::EbvCullDistancePerViewNV:
4042 case glslang::EbvLayerPerViewNV:
4043 case glslang::EbvMeshViewCountNV:
4044 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004045#endif
David Netoa901ffe2016-06-08 14:11:40 +01004046 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4047 // Alternately, we could just call this for any glslang built-in, since the
4048 // capability already guards against duplicates.
4049 TranslateBuiltInDecoration(glslangBuiltIn, false);
4050 break;
4051 default:
4052 // Capabilities were already generated when the struct was declared.
4053 break;
4054 }
John Kessenichebb50532016-05-16 19:22:05 -06004055}
4056
John Kessenich6fccb3c2016-09-19 16:01:41 -06004057bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004058{
John Kessenicheee9d532016-09-19 18:09:30 -06004059 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004060}
4061
John Kessenichd41993d2017-09-10 15:21:05 -06004062// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004063// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4064// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004065bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004066{
John Kessenich6a14f782017-12-04 02:48:10 -07004067 assert(qualifier == glslang::EvqIn ||
4068 qualifier == glslang::EvqOut ||
4069 qualifier == glslang::EvqInOut ||
4070 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004071 return qualifier != glslang::EvqConstReadOnly;
4072}
4073
4074// Is parameter pass-by-original?
4075bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4076 bool implicitThisParam)
4077{
4078 if (implicitThisParam) // implicit this
4079 return true;
4080 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004081 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004082 return paramType.containsOpaque() || // sampler, etc.
4083 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4084}
4085
John Kessenich140f3df2015-06-26 16:58:36 -06004086// Make all the functions, skeletally, without actually visiting their bodies.
4087void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4088{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004089 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004090 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4091 if (paramPrecision != spv::NoPrecision)
4092 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004093 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004094 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004095 // Original and non-writable params pass the pointer directly and
4096 // use restrict/aliased, others are stored to a pointer in Function
4097 // memory and use RestrictPointer/AliasedPointer.
4098 if (originalParam(type.getQualifier().storage, type, false) ||
4099 !writableParam(type.getQualifier().storage)) {
4100 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4101 } else {
4102 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4103 }
4104 }
John Kessenichfad62972017-07-18 02:35:46 -06004105 };
4106
John Kessenich140f3df2015-06-26 16:58:36 -06004107 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4108 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004109 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004110 continue;
4111
4112 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004113 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004114 //
qining25262b32016-05-06 17:25:16 -04004115 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004116 // function. What it is an address of varies:
4117 //
John Kessenich4bf71552016-09-02 11:20:21 -06004118 // - "in" parameters not marked as "const" can be written to without modifying the calling
4119 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004120 //
4121 // - "const in" parameters can just be the r-value, as no writes need occur.
4122 //
John Kessenich4bf71552016-09-02 11:20:21 -06004123 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4124 // 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 -06004125
4126 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004127 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004128 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4129
John Kessenichfad62972017-07-18 02:35:46 -06004130 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4131 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06004132
John Kessenichfad62972017-07-18 02:35:46 -06004133 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004134 for (int p = 0; p < (int)parameters.size(); ++p) {
4135 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4136 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004137 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004138 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004139 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004140 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4141 else
John Kessenich4bf71552016-09-02 11:20:21 -06004142 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004143 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004144 paramTypes.push_back(typeId);
4145 }
4146
4147 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004148 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4149 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004150 glslFunction->getName().c_str(), paramTypes,
4151 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004152 if (implicitThis)
4153 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004154
4155 // Track function to emit/call later
4156 functionMap[glslFunction->getName().c_str()] = function;
4157
4158 // Set the parameter id's
4159 for (int p = 0; p < (int)parameters.size(); ++p) {
4160 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4161 // give a name too
4162 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004163
4164 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4165 if (paramType.containsBasicType(glslang::EbtInt8) ||
4166 paramType.containsBasicType(glslang::EbtUint8))
4167 builder.addCapability(spv::CapabilityInt8);
4168 if (paramType.containsBasicType(glslang::EbtInt16) ||
4169 paramType.containsBasicType(glslang::EbtUint16))
4170 builder.addCapability(spv::CapabilityInt16);
4171 if (paramType.containsBasicType(glslang::EbtFloat16))
4172 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004173 }
4174 }
4175}
4176
4177// Process all the initializers, while skipping the functions and link objects
4178void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4179{
4180 builder.setBuildPoint(shaderEntry->getLastBlock());
4181 for (int i = 0; i < (int)initializers.size(); ++i) {
4182 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4183 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4184
4185 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004186 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004187 initializer->traverse(this);
4188 }
4189 }
4190}
4191
4192// Process all the functions, while skipping initializers.
4193void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4194{
4195 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4196 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004197 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004198 node->traverse(this);
4199 }
4200}
4201
4202void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4203{
qining25262b32016-05-06 17:25:16 -04004204 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004205 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004206 currentFunction = functionMap[node->getName().c_str()];
4207 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004208 builder.setBuildPoint(functionBlock);
4209}
4210
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004211void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004212{
Rex Xufc618912015-09-09 16:42:49 +08004213 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004214
4215 glslang::TSampler sampler = {};
4216 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004217#ifdef AMD_EXTENSIONS
4218 bool f16ShadowCompare = false;
4219#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004220 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004221 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4222 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004223#ifdef AMD_EXTENSIONS
4224 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4225#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004226 }
4227
John Kessenich140f3df2015-06-26 16:58:36 -06004228 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4229 builder.clearAccessChain();
4230 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004231
4232 // Special case l-value operands
4233 bool lvalue = false;
4234 switch (node.getOp()) {
4235 case glslang::EOpImageAtomicAdd:
4236 case glslang::EOpImageAtomicMin:
4237 case glslang::EOpImageAtomicMax:
4238 case glslang::EOpImageAtomicAnd:
4239 case glslang::EOpImageAtomicOr:
4240 case glslang::EOpImageAtomicXor:
4241 case glslang::EOpImageAtomicExchange:
4242 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004243 case glslang::EOpImageAtomicLoad:
4244 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004245 if (i == 0)
4246 lvalue = true;
4247 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004248 case glslang::EOpSparseImageLoad:
4249 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4250 lvalue = true;
4251 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004252#ifdef AMD_EXTENSIONS
4253 case glslang::EOpSparseTexture:
4254 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4255 lvalue = true;
4256 break;
4257 case glslang::EOpSparseTextureClamp:
4258 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4259 lvalue = true;
4260 break;
4261 case glslang::EOpSparseTextureLod:
4262 case glslang::EOpSparseTextureOffset:
4263 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4264 lvalue = true;
4265 break;
4266#else
Rex Xu48edadf2015-12-31 16:11:41 +08004267 case glslang::EOpSparseTexture:
4268 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4269 lvalue = true;
4270 break;
4271 case glslang::EOpSparseTextureClamp:
4272 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4273 lvalue = true;
4274 break;
4275 case glslang::EOpSparseTextureLod:
4276 case glslang::EOpSparseTextureOffset:
4277 if (i == 3)
4278 lvalue = true;
4279 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004280#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004281 case glslang::EOpSparseTextureFetch:
4282 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4283 lvalue = true;
4284 break;
4285 case glslang::EOpSparseTextureFetchOffset:
4286 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4287 lvalue = true;
4288 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004289#ifdef AMD_EXTENSIONS
4290 case glslang::EOpSparseTextureLodOffset:
4291 case glslang::EOpSparseTextureGrad:
4292 case glslang::EOpSparseTextureOffsetClamp:
4293 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4294 lvalue = true;
4295 break;
4296 case glslang::EOpSparseTextureGradOffset:
4297 case glslang::EOpSparseTextureGradClamp:
4298 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4299 lvalue = true;
4300 break;
4301 case glslang::EOpSparseTextureGradOffsetClamp:
4302 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4303 lvalue = true;
4304 break;
4305#else
Rex Xu48edadf2015-12-31 16:11:41 +08004306 case glslang::EOpSparseTextureLodOffset:
4307 case glslang::EOpSparseTextureGrad:
4308 case glslang::EOpSparseTextureOffsetClamp:
4309 if (i == 4)
4310 lvalue = true;
4311 break;
4312 case glslang::EOpSparseTextureGradOffset:
4313 case glslang::EOpSparseTextureGradClamp:
4314 if (i == 5)
4315 lvalue = true;
4316 break;
4317 case glslang::EOpSparseTextureGradOffsetClamp:
4318 if (i == 6)
4319 lvalue = true;
4320 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004321#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004322 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004323 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4324 lvalue = true;
4325 break;
4326 case glslang::EOpSparseTextureGatherOffset:
4327 case glslang::EOpSparseTextureGatherOffsets:
4328 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4329 lvalue = true;
4330 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004331#ifdef AMD_EXTENSIONS
4332 case glslang::EOpSparseTextureGatherLod:
4333 if (i == 3)
4334 lvalue = true;
4335 break;
4336 case glslang::EOpSparseTextureGatherLodOffset:
4337 case glslang::EOpSparseTextureGatherLodOffsets:
4338 if (i == 4)
4339 lvalue = true;
4340 break;
Rex Xu129799a2017-07-05 17:23:28 +08004341 case glslang::EOpSparseImageLoadLod:
4342 if (i == 3)
4343 lvalue = true;
4344 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004345#endif
Chao Chen3a137962018-09-19 11:41:27 -07004346#ifdef NV_EXTENSIONS
4347 case glslang::EOpImageSampleFootprintNV:
4348 if (i == 4)
4349 lvalue = true;
4350 break;
4351 case glslang::EOpImageSampleFootprintClampNV:
4352 case glslang::EOpImageSampleFootprintLodNV:
4353 if (i == 5)
4354 lvalue = true;
4355 break;
4356 case glslang::EOpImageSampleFootprintGradNV:
4357 if (i == 6)
4358 lvalue = true;
4359 break;
4360 case glslang::EOpImageSampleFootprintGradClampNV:
4361 if (i == 7)
4362 lvalue = true;
4363 break;
4364#endif
Rex Xufc618912015-09-09 16:42:49 +08004365 default:
4366 break;
4367 }
4368
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004369 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004370 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004371 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4372 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4373 } else
John Kessenich32cfd492016-02-02 12:37:46 -07004374 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004375 }
4376}
4377
John Kessenichfc51d282015-08-19 13:34:18 -06004378void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004379{
John Kessenichfc51d282015-08-19 13:34:18 -06004380 builder.clearAccessChain();
4381 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004382 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004383}
John Kessenich140f3df2015-06-26 16:58:36 -06004384
John Kessenichfc51d282015-08-19 13:34:18 -06004385spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4386{
John Kesseniche485c7a2017-05-31 18:50:53 -06004387 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004388 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004389
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004390 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004391
John Kessenichfc51d282015-08-19 13:34:18 -06004392 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004393
John Kessenichf43c7392019-03-31 10:51:57 -06004394 const glslang::TType &imageType = node->getAsAggregate()
4395 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4396 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004397 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004398#ifdef AMD_EXTENSIONS
4399 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004400 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4401 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004402#endif
4403
John Kessenichf43c7392019-03-31 10:51:57 -06004404 const auto signExtensionMask = [&]() {
4405 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4406 if (sampler.type == glslang::EbtUint)
4407 return spv::ImageOperandsZeroExtendMask;
4408 else if (sampler.type == glslang::EbtInt)
4409 return spv::ImageOperandsSignExtendMask;
4410 }
4411 return spv::ImageOperandsMaskNone;
4412 };
4413
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004414 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4415
John Kessenichfc51d282015-08-19 13:34:18 -06004416 std::vector<spv::Id> arguments;
4417 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004418 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004419 else
4420 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004421 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004422
4423 spv::Builder::TextureParameters params = { };
4424 params.sampler = arguments[0];
4425
Rex Xu04db3f52015-09-16 11:44:02 +08004426 glslang::TCrackedTextureOp cracked;
4427 node->crackTexture(sampler, cracked);
4428
amhagan05506bb2017-06-13 16:53:02 -04004429 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004430
John Kessenichfc51d282015-08-19 13:34:18 -06004431 // Check for queries
4432 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004433 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4434 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004435 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004436
John Kessenichfc51d282015-08-19 13:34:18 -06004437 switch (node->getOp()) {
4438 case glslang::EOpImageQuerySize:
4439 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004440 if (arguments.size() > 1) {
4441 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004442 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004443 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004444 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004445 case glslang::EOpImageQuerySamples:
4446 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004447 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004448 case glslang::EOpTextureQueryLod:
4449 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004450 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004451 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004452 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004453 case glslang::EOpSparseTexelsResident:
4454 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004455 default:
4456 assert(0);
4457 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004458 }
John Kessenich140f3df2015-06-26 16:58:36 -06004459 }
4460
LoopDawg4425f242018-02-18 11:40:01 -07004461 int components = node->getType().getVectorSize();
4462
4463 if (node->getOp() == glslang::EOpTextureFetch) {
4464 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4465 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4466 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4467 // here around e.g. which ones return scalars or other types.
4468 components = 4;
4469 }
4470
4471 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4472
4473 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4474
Rex Xufc618912015-09-09 16:42:49 +08004475 // Check for image functions other than queries
4476 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004477 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004478 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004479 spv::IdImmediate image = { true, *(opIt++) };
4480 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004481
4482 // Handle subpass operations
4483 // TODO: GLSL should change to have the "MS" only on the type rather than the
4484 // built-in function.
4485 if (cracked.subpass) {
4486 // add on the (0,0) coordinate
4487 spv::Id zero = builder.makeIntConstant(0);
4488 std::vector<spv::Id> comps;
4489 comps.push_back(zero);
4490 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004491 spv::IdImmediate coord = { true,
4492 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4493 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004494 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4495 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004496 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004497 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4498 }
4499 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004500 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004501 if (sampler.ms) {
4502 spv::IdImmediate imageOperand = { true, *(opIt++) };
4503 operands.push_back(imageOperand);
4504 }
John Kessenich6c292d32016-02-15 20:58:50 -07004505 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004506 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4507 builder.setPrecision(result, precision);
4508 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004509 }
4510
John Kessenich149afc32018-08-14 13:31:43 -06004511 spv::IdImmediate coord = { true, *(opIt++) };
4512 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004513#ifdef AMD_EXTENSIONS
4514 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4515#else
John Kessenich56bab042015-09-16 10:54:31 -06004516 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004517#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004518 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004519 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004520 mask = mask | spv::ImageOperandsSampleMask;
4521 }
Rex Xu129799a2017-07-05 17:23:28 +08004522#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004523 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004524 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4525 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004526 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004527 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004528#endif
4529 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4530 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004531 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004532 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004533 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4534 operands.push_back(imageOperands);
4535 }
4536 if (mask & spv::ImageOperandsSampleMask) {
4537 spv::IdImmediate imageOperand = { true, *opIt++ };
4538 operands.push_back(imageOperand);
4539 }
4540#ifdef AMD_EXTENSIONS
4541 if (mask & spv::ImageOperandsLodMask) {
4542 spv::IdImmediate imageOperand = { true, *opIt++ };
4543 operands.push_back(imageOperand);
4544 }
4545#endif
4546 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004547 spv::IdImmediate imageOperand = { true,
4548 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004549 operands.push_back(imageOperand);
4550 }
4551
John Kessenich149afc32018-08-14 13:31:43 -06004552 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004553 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004554
John Kessenich149afc32018-08-14 13:31:43 -06004555 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004556 builder.setPrecision(result[0], precision);
4557
4558 // If needed, add a conversion constructor to the proper size.
4559 if (components != node->getType().getVectorSize())
4560 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4561
4562 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004563#ifdef AMD_EXTENSIONS
4564 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4565#else
John Kessenich56bab042015-09-16 10:54:31 -06004566 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004567#endif
Rex Xu129799a2017-07-05 17:23:28 +08004568
Jeff Bolz36831c92018-09-05 10:11:41 -05004569 // Push the texel value before the operands
4570#ifdef AMD_EXTENSIONS
4571 if (sampler.ms || cracked.lod) {
4572#else
4573 if (sampler.ms) {
4574#endif
John Kessenich149afc32018-08-14 13:31:43 -06004575 spv::IdImmediate texel = { true, *(opIt + 1) };
4576 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004577 } else {
4578 spv::IdImmediate texel = { true, *opIt };
4579 operands.push_back(texel);
4580 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004581
4582 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4583 if (sampler.ms) {
4584 mask = mask | spv::ImageOperandsSampleMask;
4585 }
4586#ifdef AMD_EXTENSIONS
4587 if (cracked.lod) {
4588 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4589 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4590 mask = mask | spv::ImageOperandsLodMask;
4591 }
4592#endif
4593 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4594 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004595 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004596 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004597 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4598 operands.push_back(imageOperands);
4599 }
4600 if (mask & spv::ImageOperandsSampleMask) {
4601 spv::IdImmediate imageOperand = { true, *opIt++ };
4602 operands.push_back(imageOperand);
4603 }
4604#ifdef AMD_EXTENSIONS
4605 if (mask & spv::ImageOperandsLodMask) {
4606 spv::IdImmediate imageOperand = { true, *opIt++ };
4607 operands.push_back(imageOperand);
4608 }
4609#endif
4610 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004611 spv::IdImmediate imageOperand = { true,
4612 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004613 operands.push_back(imageOperand);
4614 }
4615
John Kessenich56bab042015-09-16 10:54:31 -06004616 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004617 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004618 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004619 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004620#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004621 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4622 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004623#else
Rex Xu5eafa472016-02-19 22:24:03 +08004624 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004625#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004626 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004627 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004628 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4629
Jeff Bolz36831c92018-09-05 10:11:41 -05004630 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004631 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004632 mask = mask | spv::ImageOperandsSampleMask;
4633 }
Rex Xu129799a2017-07-05 17:23:28 +08004634#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004635 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004636 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4637 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4638
Jeff Bolz36831c92018-09-05 10:11:41 -05004639 mask = mask | spv::ImageOperandsLodMask;
4640 }
4641#endif
4642 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4643 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004644 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004645 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004646 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004647 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004648 }
4649 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004650 spv::IdImmediate imageOperand = { true, *opIt++ };
4651 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004652 }
4653#ifdef AMD_EXTENSIONS
4654 if (mask & spv::ImageOperandsLodMask) {
4655 spv::IdImmediate imageOperand = { true, *opIt++ };
4656 operands.push_back(imageOperand);
4657 }
Rex Xu129799a2017-07-05 17:23:28 +08004658#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004659 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4660 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4661 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004662 }
4663
4664 // Create the return type that was a special structure
4665 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004666 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004667 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4668 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4669
4670 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4671
4672 // Decode the return type
4673 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4674 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004675 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004676 // Process image atomic operations
4677
4678 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4679 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004680 // For non-MS, the sample value should be 0
4681 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4682 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004683
Jeff Bolz36831c92018-09-05 10:11:41 -05004684 spv::Id resultTypeId;
4685 // imageAtomicStore has a void return type so base the pointer type on
4686 // the type of the value operand.
4687 if (node->getOp() == glslang::EOpImageAtomicStore) {
4688 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4689 } else {
4690 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4691 }
John Kessenich56bab042015-09-16 10:54:31 -06004692 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004693
4694 std::vector<spv::Id> operands;
4695 operands.push_back(pointer);
4696 for (; opIt != arguments.end(); ++opIt)
4697 operands.push_back(*opIt);
4698
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004699 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004700 }
4701 }
4702
amhagan05506bb2017-06-13 16:53:02 -04004703#ifdef AMD_EXTENSIONS
4704 // Check for fragment mask functions other than queries
4705 if (cracked.fragMask) {
4706 assert(sampler.ms);
4707
4708 auto opIt = arguments.begin();
4709 std::vector<spv::Id> operands;
4710
4711 // Extract the image if necessary
4712 if (builder.isSampledImage(params.sampler))
4713 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4714
4715 operands.push_back(params.sampler);
4716 ++opIt;
4717
4718 if (sampler.isSubpass()) {
4719 // add on the (0,0) coordinate
4720 spv::Id zero = builder.makeIntConstant(0);
4721 std::vector<spv::Id> comps;
4722 comps.push_back(zero);
4723 comps.push_back(zero);
4724 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4725 }
4726
4727 for (; opIt != arguments.end(); ++opIt)
4728 operands.push_back(*opIt);
4729
4730 spv::Op fragMaskOp = spv::OpNop;
4731 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4732 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4733 else if (node->getOp() == glslang::EOpFragmentFetch)
4734 fragMaskOp = spv::OpFragmentFetchAMD;
4735
4736 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4737 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4738 return builder.createOp(fragMaskOp, resultType(), operands);
4739 }
4740#endif
4741
Rex Xufc618912015-09-09 16:42:49 +08004742 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004743 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004744#ifdef NV_EXTENSIONS
4745 bool imageFootprint = node->isImageFootprint();
4746#endif
4747
Rex Xu71519fe2015-11-11 15:35:47 +08004748 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4749
John Kessenichfc51d282015-08-19 13:34:18 -06004750 // check for bias argument
4751 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004752#ifdef AMD_EXTENSIONS
4753 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4754#else
Rex Xu71519fe2015-11-11 15:35:47 +08004755 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004756#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004757 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004758#ifdef AMD_EXTENSIONS
4759 if (cracked.gather)
4760 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004761
4762 if (f16ShadowCompare)
4763 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004764#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004765 if (cracked.offset)
4766 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004767#ifdef AMD_EXTENSIONS
4768 else if (cracked.offsets)
4769 ++nonBiasArgCount;
4770#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004771 if (cracked.grad)
4772 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004773 if (cracked.lodClamp)
4774 ++nonBiasArgCount;
4775 if (sparse)
4776 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004777#ifdef NV_EXTENSIONS
4778 if (imageFootprint)
4779 //Following three extra arguments
4780 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4781 nonBiasArgCount += 3;
4782#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004783 if ((int)arguments.size() > nonBiasArgCount)
4784 bias = true;
4785 }
4786
John Kessenicha5c33d62016-06-02 23:45:21 -06004787 // See if the sampler param should really be just the SPV image part
4788 if (cracked.fetch) {
4789 // a fetch needs to have the image extracted first
4790 if (builder.isSampledImage(params.sampler))
4791 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4792 }
4793
Rex Xu225e0fc2016-11-17 17:47:59 +08004794#ifdef AMD_EXTENSIONS
4795 if (cracked.gather) {
4796 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4797 if (bias || cracked.lod ||
4798 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4799 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004800 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004801 }
4802 }
4803#endif
4804
John Kessenichfc51d282015-08-19 13:34:18 -06004805 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004806
John Kessenichfc51d282015-08-19 13:34:18 -06004807 params.coords = arguments[1];
4808 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004809 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004810
4811 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004812#ifdef AMD_EXTENSIONS
4813 if (cubeCompare || f16ShadowCompare) {
4814#else
Rex Xu48edadf2015-12-31 16:11:41 +08004815 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004816#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004817 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004818 ++extraArgs;
4819 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004820 params.Dref = arguments[2];
4821 ++extraArgs;
4822 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004823 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004824 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004825 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004826 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004827 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004828 dRefComp = builder.getNumComponents(params.coords) - 1;
4829 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004830 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4831 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004832
4833 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004834 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004835 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004836 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004837 } else if (glslangIntermediate->getStage() != EShLangFragment
4838#ifdef NV_EXTENSIONS
4839 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4840 && !(glslangIntermediate->getStage() == EShLangCompute &&
4841 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4842#endif
4843 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004844 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4845 noImplicitLod = true;
4846 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004847
4848 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004849 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004850 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004851 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004852 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004853
4854 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004855 if (cracked.grad) {
4856 params.gradX = arguments[2 + extraArgs];
4857 params.gradY = arguments[3 + extraArgs];
4858 extraArgs += 2;
4859 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004860
4861 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004862 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004863 params.offset = arguments[2 + extraArgs];
4864 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004865 } else if (cracked.offsets) {
4866 params.offsets = arguments[2 + extraArgs];
4867 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004868 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004869
4870 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004871 if (cracked.lodClamp) {
4872 params.lodClamp = arguments[2 + extraArgs];
4873 ++extraArgs;
4874 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004875 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004876 if (sparse) {
4877 params.texelOut = arguments[2 + extraArgs];
4878 ++extraArgs;
4879 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004880
John Kessenich76d4dfc2016-06-16 12:43:23 -06004881 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004882 if (cracked.gather && ! sampler.shadow) {
4883 // default component is 0, if missing, otherwise an argument
4884 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004885 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004886 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004887 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004888 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004889 }
Chao Chen3a137962018-09-19 11:41:27 -07004890#ifdef NV_EXTENSIONS
4891 spv::Id resultStruct = spv::NoResult;
4892 if (imageFootprint) {
4893 //Following three extra arguments
4894 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4895 params.granularity = arguments[2 + extraArgs];
4896 params.coarse = arguments[3 + extraArgs];
4897 resultStruct = arguments[4 + extraArgs];
4898 extraArgs += 3;
4899 }
4900#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004901 // bias
4902 if (bias) {
4903 params.bias = arguments[2 + extraArgs];
4904 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004905 }
John Kessenichfc51d282015-08-19 13:34:18 -06004906
Chao Chen3a137962018-09-19 11:41:27 -07004907#ifdef NV_EXTENSIONS
4908 if (imageFootprint) {
4909 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4910 builder.addCapability(spv::CapabilityImageFootprintNV);
4911
4912
4913 //resultStructType(OpenGL type) contains 5 elements:
4914 //struct gl_TextureFootprint2DNV {
4915 // uvec2 anchor;
4916 // uvec2 offset;
4917 // uvec2 mask;
4918 // uint lod;
4919 // uint granularity;
4920 //};
4921 //or
4922 //struct gl_TextureFootprint3DNV {
4923 // uvec3 anchor;
4924 // uvec3 offset;
4925 // uvec2 mask;
4926 // uint lod;
4927 // uint granularity;
4928 //};
4929 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4930 assert(builder.isStructType(resultStructType));
4931
4932 //resType (SPIR-V type) contains 6 elements:
4933 //Member 0 must be a Boolean type scalar(LOD),
4934 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4935 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4936 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4937 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4938 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4939 std::vector<spv::Id> members;
4940 members.push_back(resultType());
4941 for (int i = 0; i < 5; i++) {
4942 members.push_back(builder.getContainedTypeId(resultStructType, i));
4943 }
4944 spv::Id resType = builder.makeStructType(members, "ResType");
4945
4946 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004947 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4948 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004949
4950 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4951 for (int i = 0; i < 5; i++) {
4952 builder.clearAccessChain();
4953 builder.setAccessChainLValue(resultStruct);
4954
4955 //Accessing to a struct we created, no coherent flag is set
4956 spv::Builder::AccessChain::CoherentFlags flags;
4957 flags.clear();
4958
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004959 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004960 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4961 }
4962 return builder.createCompositeExtract(res, resultType(), 0);
4963 }
4964#endif
4965
John Kessenich65336482016-06-16 14:06:26 -06004966 // projective component (might not to move)
4967 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4968 // are divided by the last component of P."
4969 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4970 // unused components will appear after all used components."
4971 if (cracked.proj) {
4972 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4973 int projTargetComp;
4974 switch (sampler.dim) {
4975 case glslang::Esd1D: projTargetComp = 1; break;
4976 case glslang::Esd2D: projTargetComp = 2; break;
4977 case glslang::EsdRect: projTargetComp = 2; break;
4978 default: projTargetComp = projSourceComp; break;
4979 }
4980 // copy the projective coordinate if we have to
4981 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004982 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004983 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4984 projSourceComp);
4985 params.coords = builder.createCompositeInsert(projComp, params.coords,
4986 builder.getTypeId(params.coords), projTargetComp);
4987 }
4988 }
4989
Jeff Bolz36831c92018-09-05 10:11:41 -05004990 // nonprivate
4991 if (imageType.getQualifier().nonprivate) {
4992 params.nonprivate = true;
4993 }
4994
4995 // volatile
4996 if (imageType.getQualifier().volatil) {
4997 params.volatil = true;
4998 }
4999
St0fFa1184dd2018-04-09 21:08:14 +02005000 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005001 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5002 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005003 );
LoopDawg4425f242018-02-18 11:40:01 -07005004
5005 if (components != node->getType().getVectorSize())
5006 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5007
5008 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005009}
5010
5011spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5012{
5013 // Grab the function's pointer from the previously created function
5014 spv::Function* function = functionMap[node->getName().c_str()];
5015 if (! function)
5016 return 0;
5017
5018 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5019 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5020
5021 // See comments in makeFunctions() for details about the semantics for parameter passing.
5022 //
5023 // These imply we need a four step process:
5024 // 1. Evaluate the arguments
5025 // 2. Allocate and make copies of in, out, and inout arguments
5026 // 3. Make the call
5027 // 4. Copy back the results
5028
John Kessenichd3ed90b2018-05-04 11:43:03 -06005029 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005030 std::vector<spv::Builder::AccessChain> lValues;
5031 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005032 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005033 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005034 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005035 // build l-value
5036 builder.clearAccessChain();
5037 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005038 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005039 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005040 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005041 // save l-value
5042 lValues.push_back(builder.getAccessChain());
5043 } else {
5044 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005045 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005046 }
5047 }
5048
5049 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5050 // copy the original into that space.
5051 //
5052 // Also, build up the list of actual arguments to pass in for the call
5053 int lValueCount = 0;
5054 int rValueCount = 0;
5055 std::vector<spv::Id> spvArgs;
5056 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5057 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005058 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005059 builder.setAccessChain(lValues[lValueCount]);
5060 arg = builder.accessChainGetLValue();
5061 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005062 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005063 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005064 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005065 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5066 // need to copy the input into output space
5067 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005068 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005069 builder.clearAccessChain();
5070 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005071 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005072 }
5073 ++lValueCount;
5074 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005075 // process r-value, which involves a copy for a type mismatch
5076 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5077 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5078 builder.clearAccessChain();
5079 builder.setAccessChainLValue(argCopy);
5080 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5081 arg = builder.createLoad(argCopy);
5082 } else
5083 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005084 ++rValueCount;
5085 }
5086 spvArgs.push_back(arg);
5087 }
5088
5089 // 3. Make the call.
5090 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005091 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005092
5093 // 4. Copy back out an "out" arguments.
5094 lValueCount = 0;
5095 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005096 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005097 ++lValueCount;
5098 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005099 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5100 spv::Id copy = builder.createLoad(spvArgs[a]);
5101 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005102 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005103 }
5104 ++lValueCount;
5105 }
5106 }
5107
5108 return result;
5109}
5110
5111// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005112spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005113 spv::Id typeId, spv::Id left, spv::Id right,
5114 glslang::TBasicType typeProxy, bool reduceComparison)
5115{
John Kessenich66011cb2018-03-06 16:12:04 -07005116 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5117 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005118 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005119
5120 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005121 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005122 bool comparison = false;
5123
5124 switch (op) {
5125 case glslang::EOpAdd:
5126 case glslang::EOpAddAssign:
5127 if (isFloat)
5128 binOp = spv::OpFAdd;
5129 else
5130 binOp = spv::OpIAdd;
5131 break;
5132 case glslang::EOpSub:
5133 case glslang::EOpSubAssign:
5134 if (isFloat)
5135 binOp = spv::OpFSub;
5136 else
5137 binOp = spv::OpISub;
5138 break;
5139 case glslang::EOpMul:
5140 case glslang::EOpMulAssign:
5141 if (isFloat)
5142 binOp = spv::OpFMul;
5143 else
5144 binOp = spv::OpIMul;
5145 break;
5146 case glslang::EOpVectorTimesScalar:
5147 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005148 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005149 if (builder.isVector(right))
5150 std::swap(left, right);
5151 assert(builder.isScalar(right));
5152 needMatchingVectors = false;
5153 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005154 } else if (isFloat)
5155 binOp = spv::OpFMul;
5156 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005157 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005158 break;
5159 case glslang::EOpVectorTimesMatrix:
5160 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005161 binOp = spv::OpVectorTimesMatrix;
5162 break;
5163 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005164 binOp = spv::OpMatrixTimesVector;
5165 break;
5166 case glslang::EOpMatrixTimesScalar:
5167 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005168 binOp = spv::OpMatrixTimesScalar;
5169 break;
5170 case glslang::EOpMatrixTimesMatrix:
5171 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005172 binOp = spv::OpMatrixTimesMatrix;
5173 break;
5174 case glslang::EOpOuterProduct:
5175 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005176 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005177 break;
5178
5179 case glslang::EOpDiv:
5180 case glslang::EOpDivAssign:
5181 if (isFloat)
5182 binOp = spv::OpFDiv;
5183 else if (isUnsigned)
5184 binOp = spv::OpUDiv;
5185 else
5186 binOp = spv::OpSDiv;
5187 break;
5188 case glslang::EOpMod:
5189 case glslang::EOpModAssign:
5190 if (isFloat)
5191 binOp = spv::OpFMod;
5192 else if (isUnsigned)
5193 binOp = spv::OpUMod;
5194 else
5195 binOp = spv::OpSMod;
5196 break;
5197 case glslang::EOpRightShift:
5198 case glslang::EOpRightShiftAssign:
5199 if (isUnsigned)
5200 binOp = spv::OpShiftRightLogical;
5201 else
5202 binOp = spv::OpShiftRightArithmetic;
5203 break;
5204 case glslang::EOpLeftShift:
5205 case glslang::EOpLeftShiftAssign:
5206 binOp = spv::OpShiftLeftLogical;
5207 break;
5208 case glslang::EOpAnd:
5209 case glslang::EOpAndAssign:
5210 binOp = spv::OpBitwiseAnd;
5211 break;
5212 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005213 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005214 binOp = spv::OpLogicalAnd;
5215 break;
5216 case glslang::EOpInclusiveOr:
5217 case glslang::EOpInclusiveOrAssign:
5218 binOp = spv::OpBitwiseOr;
5219 break;
5220 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005221 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005222 binOp = spv::OpLogicalOr;
5223 break;
5224 case glslang::EOpExclusiveOr:
5225 case glslang::EOpExclusiveOrAssign:
5226 binOp = spv::OpBitwiseXor;
5227 break;
5228 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005229 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005230 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005231 break;
5232
5233 case glslang::EOpLessThan:
5234 case glslang::EOpGreaterThan:
5235 case glslang::EOpLessThanEqual:
5236 case glslang::EOpGreaterThanEqual:
5237 case glslang::EOpEqual:
5238 case glslang::EOpNotEqual:
5239 case glslang::EOpVectorEqual:
5240 case glslang::EOpVectorNotEqual:
5241 comparison = true;
5242 break;
5243 default:
5244 break;
5245 }
5246
John Kessenich7c1aa102015-10-15 13:29:11 -06005247 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005248 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005249 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005250 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5251 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005252 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005253
5254 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005255 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005256 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005257
qining25262b32016-05-06 17:25:16 -04005258 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005259 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005260 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005261 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005262 }
5263
5264 if (! comparison)
5265 return 0;
5266
John Kessenich7c1aa102015-10-15 13:29:11 -06005267 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005268
John Kessenich4583b612016-08-07 19:14:22 -06005269 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005270 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5271 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005272 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005273 return result;
5274 }
John Kessenich140f3df2015-06-26 16:58:36 -06005275
5276 switch (op) {
5277 case glslang::EOpLessThan:
5278 if (isFloat)
5279 binOp = spv::OpFOrdLessThan;
5280 else if (isUnsigned)
5281 binOp = spv::OpULessThan;
5282 else
5283 binOp = spv::OpSLessThan;
5284 break;
5285 case glslang::EOpGreaterThan:
5286 if (isFloat)
5287 binOp = spv::OpFOrdGreaterThan;
5288 else if (isUnsigned)
5289 binOp = spv::OpUGreaterThan;
5290 else
5291 binOp = spv::OpSGreaterThan;
5292 break;
5293 case glslang::EOpLessThanEqual:
5294 if (isFloat)
5295 binOp = spv::OpFOrdLessThanEqual;
5296 else if (isUnsigned)
5297 binOp = spv::OpULessThanEqual;
5298 else
5299 binOp = spv::OpSLessThanEqual;
5300 break;
5301 case glslang::EOpGreaterThanEqual:
5302 if (isFloat)
5303 binOp = spv::OpFOrdGreaterThanEqual;
5304 else if (isUnsigned)
5305 binOp = spv::OpUGreaterThanEqual;
5306 else
5307 binOp = spv::OpSGreaterThanEqual;
5308 break;
5309 case glslang::EOpEqual:
5310 case glslang::EOpVectorEqual:
5311 if (isFloat)
5312 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005313 else if (isBool)
5314 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005315 else
5316 binOp = spv::OpIEqual;
5317 break;
5318 case glslang::EOpNotEqual:
5319 case glslang::EOpVectorNotEqual:
5320 if (isFloat)
5321 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005322 else if (isBool)
5323 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005324 else
5325 binOp = spv::OpINotEqual;
5326 break;
5327 default:
5328 break;
5329 }
5330
qining25262b32016-05-06 17:25:16 -04005331 if (binOp != spv::OpNop) {
5332 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005333 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005334 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005335 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005336 }
John Kessenich140f3df2015-06-26 16:58:36 -06005337
5338 return 0;
5339}
5340
John Kessenich04bb8a02015-12-12 12:28:14 -07005341//
5342// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5343// These can be any of:
5344//
5345// matrix * scalar
5346// scalar * matrix
5347// matrix * matrix linear algebraic
5348// matrix * vector
5349// vector * matrix
5350// matrix * matrix componentwise
5351// matrix op matrix op in {+, -, /}
5352// matrix op scalar op in {+, -, /}
5353// scalar op matrix op in {+, -, /}
5354//
John Kessenichead86222018-03-28 18:01:20 -06005355spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5356 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005357{
5358 bool firstClass = true;
5359
5360 // First, handle first-class matrix operations (* and matrix/scalar)
5361 switch (op) {
5362 case spv::OpFDiv:
5363 if (builder.isMatrix(left) && builder.isScalar(right)) {
5364 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005365 spv::Id resultType = builder.getTypeId(right);
5366 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005367 op = spv::OpMatrixTimesScalar;
5368 } else
5369 firstClass = false;
5370 break;
5371 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005372 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005373 std::swap(left, right);
5374 assert(builder.isScalar(right));
5375 break;
5376 case spv::OpVectorTimesMatrix:
5377 assert(builder.isVector(left));
5378 assert(builder.isMatrix(right));
5379 break;
5380 case spv::OpMatrixTimesVector:
5381 assert(builder.isMatrix(left));
5382 assert(builder.isVector(right));
5383 break;
5384 case spv::OpMatrixTimesMatrix:
5385 assert(builder.isMatrix(left));
5386 assert(builder.isMatrix(right));
5387 break;
5388 default:
5389 firstClass = false;
5390 break;
5391 }
5392
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005393 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5394 firstClass = true;
5395
qining25262b32016-05-06 17:25:16 -04005396 if (firstClass) {
5397 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005398 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005399 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005400 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005401 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005402
LoopDawg592860c2016-06-09 08:57:35 -06005403 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005404 // The result type of all of them is the same type as the (a) matrix operand.
5405 // The algorithm is to:
5406 // - break the matrix(es) into vectors
5407 // - smear any scalar to a vector
5408 // - do vector operations
5409 // - make a matrix out the vector results
5410 switch (op) {
5411 case spv::OpFAdd:
5412 case spv::OpFSub:
5413 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005414 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005415 case spv::OpFMul:
5416 {
5417 // one time set up...
5418 bool leftMat = builder.isMatrix(left);
5419 bool rightMat = builder.isMatrix(right);
5420 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5421 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5422 spv::Id scalarType = builder.getScalarTypeId(typeId);
5423 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5424 std::vector<spv::Id> results;
5425 spv::Id smearVec = spv::NoResult;
5426 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005427 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005428 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005429 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005430
5431 // do each vector op
5432 for (unsigned int c = 0; c < numCols; ++c) {
5433 std::vector<unsigned int> indexes;
5434 indexes.push_back(c);
5435 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5436 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005437 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005438 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005439 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005440 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005441 }
5442
5443 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005444 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005445 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005446 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005447 }
5448 default:
5449 assert(0);
5450 return spv::NoResult;
5451 }
5452}
5453
John Kessenichead86222018-03-28 18:01:20 -06005454spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005455 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005456{
5457 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005458 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005459 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005460 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5461 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005462
5463 switch (op) {
5464 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005465 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005466 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005467 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005468 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005469 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005470 unaryOp = spv::OpSNegate;
5471 break;
5472
5473 case glslang::EOpLogicalNot:
5474 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005475 unaryOp = spv::OpLogicalNot;
5476 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005477 case glslang::EOpBitwiseNot:
5478 unaryOp = spv::OpNot;
5479 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005480
John Kessenich140f3df2015-06-26 16:58:36 -06005481 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005482 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005483 break;
5484 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005485 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005486 break;
5487 case glslang::EOpTranspose:
5488 unaryOp = spv::OpTranspose;
5489 break;
5490
5491 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005492 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005493 break;
5494 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005495 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005496 break;
5497 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005498 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005499 break;
5500 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005501 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005502 break;
5503 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005504 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005505 break;
5506 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005507 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005508 break;
5509 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005510 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005511 break;
5512 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005513 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005514 break;
5515
5516 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005517 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005518 break;
5519 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005520 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005521 break;
5522 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005523 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005524 break;
5525 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005526 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005527 break;
5528 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005529 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005530 break;
5531 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005532 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005533 break;
5534
5535 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005536 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005537 break;
5538 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005539 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005540 break;
5541
5542 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005543 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005544 break;
5545 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005546 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005547 break;
5548 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005549 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005550 break;
5551 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005552 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005553 break;
5554 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005555 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005556 break;
5557 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005558 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005559 break;
5560
5561 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005562 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005563 break;
5564 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005565 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005566 break;
5567 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005568 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005569 break;
5570 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005571 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005572 break;
5573 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005574 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005575 break;
5576 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005577 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005578 break;
5579
5580 case glslang::EOpIsNan:
5581 unaryOp = spv::OpIsNan;
5582 break;
5583 case glslang::EOpIsInf:
5584 unaryOp = spv::OpIsInf;
5585 break;
LoopDawg592860c2016-06-09 08:57:35 -06005586 case glslang::EOpIsFinite:
5587 unaryOp = spv::OpIsFinite;
5588 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005589
Rex Xucbc426e2015-12-15 16:03:10 +08005590 case glslang::EOpFloatBitsToInt:
5591 case glslang::EOpFloatBitsToUint:
5592 case glslang::EOpIntBitsToFloat:
5593 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005594 case glslang::EOpDoubleBitsToInt64:
5595 case glslang::EOpDoubleBitsToUint64:
5596 case glslang::EOpInt64BitsToDouble:
5597 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005598 case glslang::EOpFloat16BitsToInt16:
5599 case glslang::EOpFloat16BitsToUint16:
5600 case glslang::EOpInt16BitsToFloat16:
5601 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005602 unaryOp = spv::OpBitcast;
5603 break;
5604
John Kessenich140f3df2015-06-26 16:58:36 -06005605 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005606 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005607 break;
5608 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005609 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005610 break;
5611 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005612 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005613 break;
5614 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005615 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005616 break;
5617 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005618 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005619 break;
5620 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005621 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005622 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005623 case glslang::EOpPackSnorm4x8:
5624 libCall = spv::GLSLstd450PackSnorm4x8;
5625 break;
5626 case glslang::EOpUnpackSnorm4x8:
5627 libCall = spv::GLSLstd450UnpackSnorm4x8;
5628 break;
5629 case glslang::EOpPackUnorm4x8:
5630 libCall = spv::GLSLstd450PackUnorm4x8;
5631 break;
5632 case glslang::EOpUnpackUnorm4x8:
5633 libCall = spv::GLSLstd450UnpackUnorm4x8;
5634 break;
5635 case glslang::EOpPackDouble2x32:
5636 libCall = spv::GLSLstd450PackDouble2x32;
5637 break;
5638 case glslang::EOpUnpackDouble2x32:
5639 libCall = spv::GLSLstd450UnpackDouble2x32;
5640 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005641
Rex Xu8ff43de2016-04-22 16:51:45 +08005642 case glslang::EOpPackInt2x32:
5643 case glslang::EOpUnpackInt2x32:
5644 case glslang::EOpPackUint2x32:
5645 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005646 case glslang::EOpPack16:
5647 case glslang::EOpPack32:
5648 case glslang::EOpPack64:
5649 case glslang::EOpUnpack32:
5650 case glslang::EOpUnpack16:
5651 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005652 case glslang::EOpPackInt2x16:
5653 case glslang::EOpUnpackInt2x16:
5654 case glslang::EOpPackUint2x16:
5655 case glslang::EOpUnpackUint2x16:
5656 case glslang::EOpPackInt4x16:
5657 case glslang::EOpUnpackInt4x16:
5658 case glslang::EOpPackUint4x16:
5659 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005660 case glslang::EOpPackFloat2x16:
5661 case glslang::EOpUnpackFloat2x16:
5662 unaryOp = spv::OpBitcast;
5663 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005664
John Kessenich140f3df2015-06-26 16:58:36 -06005665 case glslang::EOpDPdx:
5666 unaryOp = spv::OpDPdx;
5667 break;
5668 case glslang::EOpDPdy:
5669 unaryOp = spv::OpDPdy;
5670 break;
5671 case glslang::EOpFwidth:
5672 unaryOp = spv::OpFwidth;
5673 break;
5674 case glslang::EOpDPdxFine:
5675 unaryOp = spv::OpDPdxFine;
5676 break;
5677 case glslang::EOpDPdyFine:
5678 unaryOp = spv::OpDPdyFine;
5679 break;
5680 case glslang::EOpFwidthFine:
5681 unaryOp = spv::OpFwidthFine;
5682 break;
5683 case glslang::EOpDPdxCoarse:
5684 unaryOp = spv::OpDPdxCoarse;
5685 break;
5686 case glslang::EOpDPdyCoarse:
5687 unaryOp = spv::OpDPdyCoarse;
5688 break;
5689 case glslang::EOpFwidthCoarse:
5690 unaryOp = spv::OpFwidthCoarse;
5691 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005692 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005693#ifdef AMD_EXTENSIONS
5694 if (typeProxy == glslang::EbtFloat16)
5695 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5696#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005697 libCall = spv::GLSLstd450InterpolateAtCentroid;
5698 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005699 case glslang::EOpAny:
5700 unaryOp = spv::OpAny;
5701 break;
5702 case glslang::EOpAll:
5703 unaryOp = spv::OpAll;
5704 break;
5705
5706 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005707 if (isFloat)
5708 libCall = spv::GLSLstd450FAbs;
5709 else
5710 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005711 break;
5712 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005713 if (isFloat)
5714 libCall = spv::GLSLstd450FSign;
5715 else
5716 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005717 break;
5718
John Kessenichfc51d282015-08-19 13:34:18 -06005719 case glslang::EOpAtomicCounterIncrement:
5720 case glslang::EOpAtomicCounterDecrement:
5721 case glslang::EOpAtomicCounter:
5722 {
5723 // Handle all of the atomics in one place, in createAtomicOperation()
5724 std::vector<spv::Id> operands;
5725 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005726 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005727 }
5728
John Kessenichfc51d282015-08-19 13:34:18 -06005729 case glslang::EOpBitFieldReverse:
5730 unaryOp = spv::OpBitReverse;
5731 break;
5732 case glslang::EOpBitCount:
5733 unaryOp = spv::OpBitCount;
5734 break;
5735 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005736 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005737 break;
5738 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005739 if (isUnsigned)
5740 libCall = spv::GLSLstd450FindUMsb;
5741 else
5742 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005743 break;
5744
Rex Xu574ab042016-04-14 16:53:07 +08005745 case glslang::EOpBallot:
5746 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005747 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005748 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005749 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005750#ifdef AMD_EXTENSIONS
5751 case glslang::EOpMinInvocations:
5752 case glslang::EOpMaxInvocations:
5753 case glslang::EOpAddInvocations:
5754 case glslang::EOpMinInvocationsNonUniform:
5755 case glslang::EOpMaxInvocationsNonUniform:
5756 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005757 case glslang::EOpMinInvocationsInclusiveScan:
5758 case glslang::EOpMaxInvocationsInclusiveScan:
5759 case glslang::EOpAddInvocationsInclusiveScan:
5760 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5761 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5762 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5763 case glslang::EOpMinInvocationsExclusiveScan:
5764 case glslang::EOpMaxInvocationsExclusiveScan:
5765 case glslang::EOpAddInvocationsExclusiveScan:
5766 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5767 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5768 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005769#endif
Rex Xu51596642016-09-21 18:56:12 +08005770 {
5771 std::vector<spv::Id> operands;
5772 operands.push_back(operand);
5773 return createInvocationsOperation(op, typeId, operands, typeProxy);
5774 }
John Kessenich66011cb2018-03-06 16:12:04 -07005775 case glslang::EOpSubgroupAll:
5776 case glslang::EOpSubgroupAny:
5777 case glslang::EOpSubgroupAllEqual:
5778 case glslang::EOpSubgroupBroadcastFirst:
5779 case glslang::EOpSubgroupBallot:
5780 case glslang::EOpSubgroupInverseBallot:
5781 case glslang::EOpSubgroupBallotBitCount:
5782 case glslang::EOpSubgroupBallotInclusiveBitCount:
5783 case glslang::EOpSubgroupBallotExclusiveBitCount:
5784 case glslang::EOpSubgroupBallotFindLSB:
5785 case glslang::EOpSubgroupBallotFindMSB:
5786 case glslang::EOpSubgroupAdd:
5787 case glslang::EOpSubgroupMul:
5788 case glslang::EOpSubgroupMin:
5789 case glslang::EOpSubgroupMax:
5790 case glslang::EOpSubgroupAnd:
5791 case glslang::EOpSubgroupOr:
5792 case glslang::EOpSubgroupXor:
5793 case glslang::EOpSubgroupInclusiveAdd:
5794 case glslang::EOpSubgroupInclusiveMul:
5795 case glslang::EOpSubgroupInclusiveMin:
5796 case glslang::EOpSubgroupInclusiveMax:
5797 case glslang::EOpSubgroupInclusiveAnd:
5798 case glslang::EOpSubgroupInclusiveOr:
5799 case glslang::EOpSubgroupInclusiveXor:
5800 case glslang::EOpSubgroupExclusiveAdd:
5801 case glslang::EOpSubgroupExclusiveMul:
5802 case glslang::EOpSubgroupExclusiveMin:
5803 case glslang::EOpSubgroupExclusiveMax:
5804 case glslang::EOpSubgroupExclusiveAnd:
5805 case glslang::EOpSubgroupExclusiveOr:
5806 case glslang::EOpSubgroupExclusiveXor:
5807 case glslang::EOpSubgroupQuadSwapHorizontal:
5808 case glslang::EOpSubgroupQuadSwapVertical:
5809 case glslang::EOpSubgroupQuadSwapDiagonal: {
5810 std::vector<spv::Id> operands;
5811 operands.push_back(operand);
5812 return createSubgroupOperation(op, typeId, operands, typeProxy);
5813 }
Rex Xu9d93a232016-05-05 12:30:44 +08005814#ifdef AMD_EXTENSIONS
5815 case glslang::EOpMbcnt:
5816 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5817 libCall = spv::MbcntAMD;
5818 break;
5819
5820 case glslang::EOpCubeFaceIndex:
5821 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5822 libCall = spv::CubeFaceIndexAMD;
5823 break;
5824
5825 case glslang::EOpCubeFaceCoord:
5826 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5827 libCall = spv::CubeFaceCoordAMD;
5828 break;
5829#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005830#ifdef NV_EXTENSIONS
5831 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005832 unaryOp = spv::OpGroupNonUniformPartitionNV;
5833 break;
5834#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005835 case glslang::EOpConstructReference:
5836 unaryOp = spv::OpBitcast;
5837 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005838
5839 case glslang::EOpCopyObject:
5840 unaryOp = spv::OpCopyObject;
5841 break;
5842
John Kessenich140f3df2015-06-26 16:58:36 -06005843 default:
5844 return 0;
5845 }
5846
5847 spv::Id id;
5848 if (libCall >= 0) {
5849 std::vector<spv::Id> args;
5850 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005851 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005852 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005853 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005854 }
John Kessenich140f3df2015-06-26 16:58:36 -06005855
John Kessenichead86222018-03-28 18:01:20 -06005856 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005857 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005858 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005859}
5860
John Kessenich7a53f762016-01-20 11:19:27 -07005861// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005862spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5863 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005864{
5865 // Handle unary operations vector by vector.
5866 // The result type is the same type as the original type.
5867 // The algorithm is to:
5868 // - break the matrix into vectors
5869 // - apply the operation to each vector
5870 // - make a matrix out the vector results
5871
5872 // get the types sorted out
5873 int numCols = builder.getNumColumns(operand);
5874 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005875 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5876 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005877 std::vector<spv::Id> results;
5878
5879 // do each vector op
5880 for (int c = 0; c < numCols; ++c) {
5881 std::vector<unsigned int> indexes;
5882 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005883 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5884 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005885 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005886 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005887 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005888 }
5889
5890 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005891 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005892 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005893 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005894}
5895
John Kessenichad7645f2018-06-04 19:11:25 -06005896// For converting integers where both the bitwidth and the signedness could
5897// change, but only do the width change here. The caller is still responsible
5898// for the signedness conversion.
5899spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005900{
John Kessenichad7645f2018-06-04 19:11:25 -06005901 // Get the result type width, based on the type to convert to.
5902 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005903 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005904 case glslang::EOpConvInt16ToUint8:
5905 case glslang::EOpConvIntToUint8:
5906 case glslang::EOpConvInt64ToUint8:
5907 case glslang::EOpConvUint16ToInt8:
5908 case glslang::EOpConvUintToInt8:
5909 case glslang::EOpConvUint64ToInt8:
5910 width = 8;
5911 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005912 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005913 case glslang::EOpConvIntToUint16:
5914 case glslang::EOpConvInt64ToUint16:
5915 case glslang::EOpConvUint8ToInt16:
5916 case glslang::EOpConvUintToInt16:
5917 case glslang::EOpConvUint64ToInt16:
5918 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005919 break;
5920 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005921 case glslang::EOpConvInt16ToUint:
5922 case glslang::EOpConvInt64ToUint:
5923 case glslang::EOpConvUint8ToInt:
5924 case glslang::EOpConvUint16ToInt:
5925 case glslang::EOpConvUint64ToInt:
5926 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005927 break;
5928 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005929 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005930 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005931 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005932 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005933 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005934 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005935 break;
5936
5937 default:
5938 assert(false && "Default missing");
5939 break;
5940 }
5941
John Kessenichad7645f2018-06-04 19:11:25 -06005942 // Get the conversion operation and result type,
5943 // based on the target width, but the source type.
5944 spv::Id type = spv::NoType;
5945 spv::Op convOp = spv::OpNop;
5946 switch(op) {
5947 case glslang::EOpConvInt8ToUint16:
5948 case glslang::EOpConvInt8ToUint:
5949 case glslang::EOpConvInt8ToUint64:
5950 case glslang::EOpConvInt16ToUint8:
5951 case glslang::EOpConvInt16ToUint:
5952 case glslang::EOpConvInt16ToUint64:
5953 case glslang::EOpConvIntToUint8:
5954 case glslang::EOpConvIntToUint16:
5955 case glslang::EOpConvIntToUint64:
5956 case glslang::EOpConvInt64ToUint8:
5957 case glslang::EOpConvInt64ToUint16:
5958 case glslang::EOpConvInt64ToUint:
5959 convOp = spv::OpSConvert;
5960 type = builder.makeIntType(width);
5961 break;
5962 default:
5963 convOp = spv::OpUConvert;
5964 type = builder.makeUintType(width);
5965 break;
5966 }
5967
John Kessenich66011cb2018-03-06 16:12:04 -07005968 if (vectorSize > 0)
5969 type = builder.makeVectorType(type, vectorSize);
5970
John Kessenichad7645f2018-06-04 19:11:25 -06005971 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005972}
5973
John Kessenichead86222018-03-28 18:01:20 -06005974spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5975 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005976{
5977 spv::Op convOp = spv::OpNop;
5978 spv::Id zero = 0;
5979 spv::Id one = 0;
5980
5981 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5982
5983 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005984 case glslang::EOpConvInt8ToBool:
5985 case glslang::EOpConvUint8ToBool:
5986 zero = builder.makeUint8Constant(0);
5987 zero = makeSmearedConstant(zero, vectorSize);
5988 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005989 case glslang::EOpConvInt16ToBool:
5990 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005991 zero = builder.makeUint16Constant(0);
5992 zero = makeSmearedConstant(zero, vectorSize);
5993 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5994 case glslang::EOpConvIntToBool:
5995 case glslang::EOpConvUintToBool:
5996 zero = builder.makeUintConstant(0);
5997 zero = makeSmearedConstant(zero, vectorSize);
5998 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5999 case glslang::EOpConvInt64ToBool:
6000 case glslang::EOpConvUint64ToBool:
6001 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006002 zero = makeSmearedConstant(zero, vectorSize);
6003 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6004
6005 case glslang::EOpConvFloatToBool:
6006 zero = builder.makeFloatConstant(0.0F);
6007 zero = makeSmearedConstant(zero, vectorSize);
6008 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6009
6010 case glslang::EOpConvDoubleToBool:
6011 zero = builder.makeDoubleConstant(0.0);
6012 zero = makeSmearedConstant(zero, vectorSize);
6013 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6014
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006015 case glslang::EOpConvFloat16ToBool:
6016 zero = builder.makeFloat16Constant(0.0F);
6017 zero = makeSmearedConstant(zero, vectorSize);
6018 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006019
John Kessenich140f3df2015-06-26 16:58:36 -06006020 case glslang::EOpConvBoolToFloat:
6021 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006022 zero = builder.makeFloatConstant(0.0F);
6023 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006024 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006025
John Kessenich140f3df2015-06-26 16:58:36 -06006026 case glslang::EOpConvBoolToDouble:
6027 convOp = spv::OpSelect;
6028 zero = builder.makeDoubleConstant(0.0);
6029 one = builder.makeDoubleConstant(1.0);
6030 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006031
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006032 case glslang::EOpConvBoolToFloat16:
6033 convOp = spv::OpSelect;
6034 zero = builder.makeFloat16Constant(0.0F);
6035 one = builder.makeFloat16Constant(1.0F);
6036 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006037
6038 case glslang::EOpConvBoolToInt8:
6039 zero = builder.makeInt8Constant(0);
6040 one = builder.makeInt8Constant(1);
6041 convOp = spv::OpSelect;
6042 break;
6043
6044 case glslang::EOpConvBoolToUint8:
6045 zero = builder.makeUint8Constant(0);
6046 one = builder.makeUint8Constant(1);
6047 convOp = spv::OpSelect;
6048 break;
6049
6050 case glslang::EOpConvBoolToInt16:
6051 zero = builder.makeInt16Constant(0);
6052 one = builder.makeInt16Constant(1);
6053 convOp = spv::OpSelect;
6054 break;
6055
6056 case glslang::EOpConvBoolToUint16:
6057 zero = builder.makeUint16Constant(0);
6058 one = builder.makeUint16Constant(1);
6059 convOp = spv::OpSelect;
6060 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006061
John Kessenich140f3df2015-06-26 16:58:36 -06006062 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006063 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006064 if (op == glslang::EOpConvBoolToInt64)
6065 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006066 else
6067 zero = builder.makeIntConstant(0);
6068
6069 if (op == glslang::EOpConvBoolToInt64)
6070 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006071 else
6072 one = builder.makeIntConstant(1);
6073
John Kessenich140f3df2015-06-26 16:58:36 -06006074 convOp = spv::OpSelect;
6075 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006076
John Kessenich140f3df2015-06-26 16:58:36 -06006077 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006078 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08006079 if (op == glslang::EOpConvBoolToUint64)
6080 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006081 else
6082 zero = builder.makeUintConstant(0);
6083
6084 if (op == glslang::EOpConvBoolToUint64)
6085 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006086 else
6087 one = builder.makeUintConstant(1);
6088
John Kessenich140f3df2015-06-26 16:58:36 -06006089 convOp = spv::OpSelect;
6090 break;
6091
John Kessenich66011cb2018-03-06 16:12:04 -07006092 case glslang::EOpConvInt8ToFloat16:
6093 case glslang::EOpConvInt8ToFloat:
6094 case glslang::EOpConvInt8ToDouble:
6095 case glslang::EOpConvInt16ToFloat16:
6096 case glslang::EOpConvInt16ToFloat:
6097 case glslang::EOpConvInt16ToDouble:
6098 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006099 case glslang::EOpConvIntToFloat:
6100 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006101 case glslang::EOpConvInt64ToFloat:
6102 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006103 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006104 convOp = spv::OpConvertSToF;
6105 break;
6106
John Kessenich66011cb2018-03-06 16:12:04 -07006107 case glslang::EOpConvUint8ToFloat16:
6108 case glslang::EOpConvUint8ToFloat:
6109 case glslang::EOpConvUint8ToDouble:
6110 case glslang::EOpConvUint16ToFloat16:
6111 case glslang::EOpConvUint16ToFloat:
6112 case glslang::EOpConvUint16ToDouble:
6113 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006114 case glslang::EOpConvUintToFloat:
6115 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006116 case glslang::EOpConvUint64ToFloat:
6117 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006118 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006119 convOp = spv::OpConvertUToF;
6120 break;
6121
6122 case glslang::EOpConvDoubleToFloat:
6123 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006124 case glslang::EOpConvDoubleToFloat16:
6125 case glslang::EOpConvFloat16ToDouble:
6126 case glslang::EOpConvFloatToFloat16:
6127 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06006128 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08006129 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06006130 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06006131 break;
6132
John Kessenich66011cb2018-03-06 16:12:04 -07006133 case glslang::EOpConvFloat16ToInt8:
6134 case glslang::EOpConvFloatToInt8:
6135 case glslang::EOpConvDoubleToInt8:
6136 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006137 case glslang::EOpConvFloatToInt16:
6138 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006139 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006140 case glslang::EOpConvFloatToInt:
6141 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006142 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006143 case glslang::EOpConvFloatToInt64:
6144 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006145 convOp = spv::OpConvertFToS;
6146 break;
6147
John Kessenich66011cb2018-03-06 16:12:04 -07006148 case glslang::EOpConvUint8ToInt8:
6149 case glslang::EOpConvInt8ToUint8:
6150 case glslang::EOpConvUint16ToInt16:
6151 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006152 case glslang::EOpConvUintToInt:
6153 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006154 case glslang::EOpConvUint64ToInt64:
6155 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006156 if (builder.isInSpecConstCodeGenMode()) {
6157 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006158 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6159 zero = builder.makeUint8Constant(0);
6160 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006161 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006162 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6163 zero = builder.makeUint64Constant(0);
6164 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006165 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006166 }
qining189b2032016-04-12 23:16:20 -04006167 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006168 // Use OpIAdd, instead of OpBitcast to do the conversion when
6169 // generating for OpSpecConstantOp instruction.
6170 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6171 }
6172 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006173 convOp = spv::OpBitcast;
6174 break;
6175
John Kessenich66011cb2018-03-06 16:12:04 -07006176 case glslang::EOpConvFloat16ToUint8:
6177 case glslang::EOpConvFloatToUint8:
6178 case glslang::EOpConvDoubleToUint8:
6179 case glslang::EOpConvFloat16ToUint16:
6180 case glslang::EOpConvFloatToUint16:
6181 case glslang::EOpConvDoubleToUint16:
6182 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006183 case glslang::EOpConvFloatToUint:
6184 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006185 case glslang::EOpConvFloatToUint64:
6186 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006187 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006188 convOp = spv::OpConvertFToU;
6189 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006190
John Kessenich66011cb2018-03-06 16:12:04 -07006191 case glslang::EOpConvInt8ToInt16:
6192 case glslang::EOpConvInt8ToInt:
6193 case glslang::EOpConvInt8ToInt64:
6194 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006195 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006196 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006197 case glslang::EOpConvIntToInt8:
6198 case glslang::EOpConvIntToInt16:
6199 case glslang::EOpConvIntToInt64:
6200 case glslang::EOpConvInt64ToInt8:
6201 case glslang::EOpConvInt64ToInt16:
6202 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006203 convOp = spv::OpSConvert;
6204 break;
6205
John Kessenich66011cb2018-03-06 16:12:04 -07006206 case glslang::EOpConvUint8ToUint16:
6207 case glslang::EOpConvUint8ToUint:
6208 case glslang::EOpConvUint8ToUint64:
6209 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006210 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006211 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006212 case glslang::EOpConvUintToUint8:
6213 case glslang::EOpConvUintToUint16:
6214 case glslang::EOpConvUintToUint64:
6215 case glslang::EOpConvUint64ToUint8:
6216 case glslang::EOpConvUint64ToUint16:
6217 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006218 convOp = spv::OpUConvert;
6219 break;
6220
John Kessenich66011cb2018-03-06 16:12:04 -07006221 case glslang::EOpConvInt8ToUint16:
6222 case glslang::EOpConvInt8ToUint:
6223 case glslang::EOpConvInt8ToUint64:
6224 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006225 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006226 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006227 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006228 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006229 case glslang::EOpConvIntToUint64:
6230 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006231 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006232 case glslang::EOpConvInt64ToUint:
6233 case glslang::EOpConvUint8ToInt16:
6234 case glslang::EOpConvUint8ToInt:
6235 case glslang::EOpConvUint8ToInt64:
6236 case glslang::EOpConvUint16ToInt8:
6237 case glslang::EOpConvUint16ToInt:
6238 case glslang::EOpConvUint16ToInt64:
6239 case glslang::EOpConvUintToInt8:
6240 case glslang::EOpConvUintToInt16:
6241 case glslang::EOpConvUintToInt64:
6242 case glslang::EOpConvUint64ToInt8:
6243 case glslang::EOpConvUint64ToInt16:
6244 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006245 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006246 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006247
6248 if (builder.isInSpecConstCodeGenMode()) {
6249 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006250 switch(op) {
6251 case glslang::EOpConvInt16ToUint8:
6252 case glslang::EOpConvIntToUint8:
6253 case glslang::EOpConvInt64ToUint8:
6254 case glslang::EOpConvUint16ToInt8:
6255 case glslang::EOpConvUintToInt8:
6256 case glslang::EOpConvUint64ToInt8:
6257 zero = builder.makeUint8Constant(0);
6258 break;
6259 case glslang::EOpConvInt8ToUint16:
6260 case glslang::EOpConvIntToUint16:
6261 case glslang::EOpConvInt64ToUint16:
6262 case glslang::EOpConvUint8ToInt16:
6263 case glslang::EOpConvUintToInt16:
6264 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006265 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006266 break;
6267 case glslang::EOpConvInt8ToUint:
6268 case glslang::EOpConvInt16ToUint:
6269 case glslang::EOpConvInt64ToUint:
6270 case glslang::EOpConvUint8ToInt:
6271 case glslang::EOpConvUint16ToInt:
6272 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006273 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006274 break;
6275 case glslang::EOpConvInt8ToUint64:
6276 case glslang::EOpConvInt16ToUint64:
6277 case glslang::EOpConvIntToUint64:
6278 case glslang::EOpConvUint8ToInt64:
6279 case glslang::EOpConvUint16ToInt64:
6280 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006281 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006282 break;
6283 default:
6284 assert(false && "Default missing");
6285 break;
6286 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006287 zero = makeSmearedConstant(zero, vectorSize);
6288 // Use OpIAdd, instead of OpBitcast to do the conversion when
6289 // generating for OpSpecConstantOp instruction.
6290 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6291 }
6292 // For normal run-time conversion instruction, use OpBitcast.
6293 convOp = spv::OpBitcast;
6294 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006295 case glslang::EOpConvUint64ToPtr:
6296 convOp = spv::OpConvertUToPtr;
6297 break;
6298 case glslang::EOpConvPtrToUint64:
6299 convOp = spv::OpConvertPtrToU;
6300 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006301 default:
6302 break;
6303 }
6304
6305 spv::Id result = 0;
6306 if (convOp == spv::OpNop)
6307 return result;
6308
6309 if (convOp == spv::OpSelect) {
6310 zero = makeSmearedConstant(zero, vectorSize);
6311 one = makeSmearedConstant(one, vectorSize);
6312 result = builder.createTriOp(convOp, destType, operand, one, zero);
6313 } else
6314 result = builder.createUnaryOp(convOp, destType, operand);
6315
John Kessenichead86222018-03-28 18:01:20 -06006316 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006317 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006318 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006319}
6320
6321spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6322{
6323 if (vectorSize == 0)
6324 return constant;
6325
6326 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6327 std::vector<spv::Id> components;
6328 for (int c = 0; c < vectorSize; ++c)
6329 components.push_back(constant);
6330 return builder.makeCompositeConstant(vectorTypeId, components);
6331}
6332
John Kessenich426394d2015-07-23 10:22:48 -06006333// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006334spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006335{
6336 spv::Op opCode = spv::OpNop;
6337
6338 switch (op) {
6339 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006340 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006341 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006342 opCode = spv::OpAtomicIAdd;
6343 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006344 case glslang::EOpAtomicCounterSubtract:
6345 opCode = spv::OpAtomicISub;
6346 break;
John Kessenich426394d2015-07-23 10:22:48 -06006347 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006348 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006349 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006350 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006351 break;
6352 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006353 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006354 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006355 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006356 break;
6357 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006358 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006359 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006360 opCode = spv::OpAtomicAnd;
6361 break;
6362 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006363 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006364 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006365 opCode = spv::OpAtomicOr;
6366 break;
6367 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006368 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006369 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006370 opCode = spv::OpAtomicXor;
6371 break;
6372 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006373 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006374 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006375 opCode = spv::OpAtomicExchange;
6376 break;
6377 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006378 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006379 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006380 opCode = spv::OpAtomicCompareExchange;
6381 break;
6382 case glslang::EOpAtomicCounterIncrement:
6383 opCode = spv::OpAtomicIIncrement;
6384 break;
6385 case glslang::EOpAtomicCounterDecrement:
6386 opCode = spv::OpAtomicIDecrement;
6387 break;
6388 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006389 case glslang::EOpImageAtomicLoad:
6390 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006391 opCode = spv::OpAtomicLoad;
6392 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006393 case glslang::EOpAtomicStore:
6394 case glslang::EOpImageAtomicStore:
6395 opCode = spv::OpAtomicStore;
6396 break;
John Kessenich426394d2015-07-23 10:22:48 -06006397 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006398 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006399 break;
6400 }
6401
Rex Xue8fe8b02017-09-26 15:42:56 +08006402 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6403 builder.addCapability(spv::CapabilityInt64Atomics);
6404
John Kessenich426394d2015-07-23 10:22:48 -06006405 // Sort out the operands
6406 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006407 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006408 // - compare-exchange swaps the value and comparator
6409 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006410 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006411 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6412 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6413 spv::Id scopeId;
6414 if (glslangIntermediate->usingVulkanMemoryModel()) {
6415 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6416 } else {
6417 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6418 }
6419 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006420 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006421 spv::Id semanticsId2 = semanticsId;
6422
6423 pointerId = operands[0];
6424 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6425 // no additional operands
6426 } else if (opCode == spv::OpAtomicCompareExchange) {
6427 compareId = operands[1];
6428 valueId = operands[2];
6429 if (operands.size() > 3) {
6430 scopeId = operands[3];
6431 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6432 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6433 }
6434 } else if (opCode == spv::OpAtomicLoad) {
6435 if (operands.size() > 1) {
6436 scopeId = operands[1];
6437 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6438 }
6439 } else {
6440 // atomic store or RMW
6441 valueId = operands[1];
6442 if (operands.size() > 2) {
6443 scopeId = operands[2];
6444 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6445 }
Rex Xu04db3f52015-09-16 11:44:02 +08006446 }
John Kessenich426394d2015-07-23 10:22:48 -06006447
Jeff Bolz36831c92018-09-05 10:11:41 -05006448 // Check for capabilities
6449 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006450 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6451 spv::MemorySemanticsMakeVisibleKHRMask |
6452 spv::MemorySemanticsOutputMemoryKHRMask |
6453 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006454 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6455 }
John Kessenich426394d2015-07-23 10:22:48 -06006456
Jeff Bolz36831c92018-09-05 10:11:41 -05006457 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6458 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6459 }
John Kessenich48d6e792017-10-06 21:21:48 -06006460
Jeff Bolz36831c92018-09-05 10:11:41 -05006461 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6462 spvAtomicOperands.push_back(pointerId);
6463 spvAtomicOperands.push_back(scopeId);
6464 spvAtomicOperands.push_back(semanticsId);
6465 if (opCode == spv::OpAtomicCompareExchange) {
6466 spvAtomicOperands.push_back(semanticsId2);
6467 spvAtomicOperands.push_back(valueId);
6468 spvAtomicOperands.push_back(compareId);
6469 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6470 spvAtomicOperands.push_back(valueId);
6471 }
John Kessenich48d6e792017-10-06 21:21:48 -06006472
Jeff Bolz36831c92018-09-05 10:11:41 -05006473 if (opCode == spv::OpAtomicStore) {
6474 builder.createNoResultOp(opCode, spvAtomicOperands);
6475 return 0;
6476 } else {
6477 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6478
6479 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6480 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6481 if (op == glslang::EOpAtomicCounterDecrement)
6482 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6483
6484 return resultId;
6485 }
John Kessenich426394d2015-07-23 10:22:48 -06006486}
6487
John Kessenich91cef522016-05-05 16:45:40 -06006488// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006489spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006490{
Corentin Walleze7061422018-08-08 15:20:15 +02006491#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006492 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6493 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006494#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006495
Rex Xu51596642016-09-21 18:56:12 +08006496 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006497 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006498 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6499
chaocf200da82016-12-20 12:44:35 -08006500 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6501 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006502 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6503 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006504 } else if (op == glslang::EOpAnyInvocation ||
6505 op == glslang::EOpAllInvocations ||
6506 op == glslang::EOpAllInvocationsEqual) {
6507 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6508 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006509 } else {
6510 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006511#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006512 if (op == glslang::EOpMinInvocationsNonUniform ||
6513 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006514 op == glslang::EOpAddInvocationsNonUniform ||
6515 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6516 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6517 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6518 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6519 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6520 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006521 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006522#endif
Rex Xu51596642016-09-21 18:56:12 +08006523
Rex Xu9d93a232016-05-05 12:30:44 +08006524#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006525 switch (op) {
6526 case glslang::EOpMinInvocations:
6527 case glslang::EOpMaxInvocations:
6528 case glslang::EOpAddInvocations:
6529 case glslang::EOpMinInvocationsNonUniform:
6530 case glslang::EOpMaxInvocationsNonUniform:
6531 case glslang::EOpAddInvocationsNonUniform:
6532 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006533 break;
6534 case glslang::EOpMinInvocationsInclusiveScan:
6535 case glslang::EOpMaxInvocationsInclusiveScan:
6536 case glslang::EOpAddInvocationsInclusiveScan:
6537 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6538 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6539 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6540 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006541 break;
6542 case glslang::EOpMinInvocationsExclusiveScan:
6543 case glslang::EOpMaxInvocationsExclusiveScan:
6544 case glslang::EOpAddInvocationsExclusiveScan:
6545 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6546 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6547 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6548 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006549 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006550 default:
6551 break;
Rex Xu430ef402016-10-14 17:22:23 +08006552 }
John Kessenich149afc32018-08-14 13:31:43 -06006553 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6554 spvGroupOperands.push_back(scope);
6555 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006556 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006557 spvGroupOperands.push_back(groupOp);
6558 }
Rex Xu9d93a232016-05-05 12:30:44 +08006559#endif
Rex Xu51596642016-09-21 18:56:12 +08006560 }
6561
John Kessenich149afc32018-08-14 13:31:43 -06006562 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6563 spv::IdImmediate op = { true, *opIt };
6564 spvGroupOperands.push_back(op);
6565 }
John Kessenich91cef522016-05-05 16:45:40 -06006566
6567 switch (op) {
6568 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006569 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006570 break;
John Kessenich91cef522016-05-05 16:45:40 -06006571 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006572 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006573 break;
John Kessenich91cef522016-05-05 16:45:40 -06006574 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006575 opCode = spv::OpSubgroupAllEqualKHR;
6576 break;
Rex Xu51596642016-09-21 18:56:12 +08006577 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006578 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006579 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006580 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006581 break;
6582 case glslang::EOpReadFirstInvocation:
6583 opCode = spv::OpSubgroupFirstInvocationKHR;
6584 break;
6585 case glslang::EOpBallot:
6586 {
6587 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6588 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6589 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6590 //
6591 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6592 //
6593 spv::Id uintType = builder.makeUintType(32);
6594 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6595 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6596
6597 std::vector<spv::Id> components;
6598 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6599 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6600
6601 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6602 return builder.createUnaryOp(spv::OpBitcast, typeId,
6603 builder.createCompositeConstruct(uvec2Type, components));
6604 }
6605
Rex Xu9d93a232016-05-05 12:30:44 +08006606#ifdef AMD_EXTENSIONS
6607 case glslang::EOpMinInvocations:
6608 case glslang::EOpMaxInvocations:
6609 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006610 case glslang::EOpMinInvocationsInclusiveScan:
6611 case glslang::EOpMaxInvocationsInclusiveScan:
6612 case glslang::EOpAddInvocationsInclusiveScan:
6613 case glslang::EOpMinInvocationsExclusiveScan:
6614 case glslang::EOpMaxInvocationsExclusiveScan:
6615 case glslang::EOpAddInvocationsExclusiveScan:
6616 if (op == glslang::EOpMinInvocations ||
6617 op == glslang::EOpMinInvocationsInclusiveScan ||
6618 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006619 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006620 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006621 else {
6622 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006623 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006624 else
Rex Xu51596642016-09-21 18:56:12 +08006625 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006626 }
Rex Xu430ef402016-10-14 17:22:23 +08006627 } else if (op == glslang::EOpMaxInvocations ||
6628 op == glslang::EOpMaxInvocationsInclusiveScan ||
6629 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006630 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006631 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006632 else {
6633 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006634 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006635 else
Rex Xu51596642016-09-21 18:56:12 +08006636 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006637 }
6638 } else {
6639 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006640 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006641 else
Rex Xu51596642016-09-21 18:56:12 +08006642 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006643 }
6644
Rex Xu2bbbe062016-08-23 15:41:05 +08006645 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006646 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006647
6648 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006649 case glslang::EOpMinInvocationsNonUniform:
6650 case glslang::EOpMaxInvocationsNonUniform:
6651 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006652 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6653 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6654 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6655 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6656 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6657 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6658 if (op == glslang::EOpMinInvocationsNonUniform ||
6659 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6660 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006661 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006662 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006663 else {
6664 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006665 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006666 else
Rex Xu51596642016-09-21 18:56:12 +08006667 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006668 }
6669 }
Rex Xu430ef402016-10-14 17:22:23 +08006670 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6671 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6672 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006673 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006674 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006675 else {
6676 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006677 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006678 else
Rex Xu51596642016-09-21 18:56:12 +08006679 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006680 }
6681 }
6682 else {
6683 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006684 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006685 else
Rex Xu51596642016-09-21 18:56:12 +08006686 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006687 }
6688
Rex Xu2bbbe062016-08-23 15:41:05 +08006689 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006690 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006691
6692 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006693#endif
John Kessenich91cef522016-05-05 16:45:40 -06006694 default:
6695 logger->missingFunctionality("invocation operation");
6696 return spv::NoResult;
6697 }
Rex Xu51596642016-09-21 18:56:12 +08006698
6699 assert(opCode != spv::OpNop);
6700 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006701}
6702
Rex Xu2bbbe062016-08-23 15:41:05 +08006703// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006704spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6705 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006706{
Rex Xub7072052016-09-26 15:53:40 +08006707#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006708 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6709 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006710 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006711 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006712 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6713 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6714 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006715#else
6716 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6717 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006718 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6719 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006720#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006721
6722 // Handle group invocation operations scalar by scalar.
6723 // The result type is the same type as the original type.
6724 // The algorithm is to:
6725 // - break the vector into scalars
6726 // - apply the operation to each scalar
6727 // - make a vector out the scalar results
6728
6729 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006730 int numComponents = builder.getNumComponents(operands[0]);
6731 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006732 std::vector<spv::Id> results;
6733
6734 // do each scalar op
6735 for (int comp = 0; comp < numComponents; ++comp) {
6736 std::vector<unsigned int> indexes;
6737 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006738 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6739 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006740 if (op == spv::OpSubgroupReadInvocationKHR) {
6741 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006742 spv::IdImmediate operand = { true, operands[1] };
6743 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006744 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006745 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6746 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006747 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006748 spv::IdImmediate operand = { true, operands[1] };
6749 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006750 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006751 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6752 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006753 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006754 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006755 spvGroupOperands.push_back(scalar);
6756 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006757
Rex Xub7072052016-09-26 15:53:40 +08006758 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006759 }
6760
6761 // put the pieces together
6762 return builder.createCompositeConstruct(typeId, results);
6763}
Rex Xu2bbbe062016-08-23 15:41:05 +08006764
John Kessenich66011cb2018-03-06 16:12:04 -07006765// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006766spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6767 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006768{
6769 // Add the required capabilities.
6770 switch (op) {
6771 case glslang::EOpSubgroupElect:
6772 builder.addCapability(spv::CapabilityGroupNonUniform);
6773 break;
6774 case glslang::EOpSubgroupAll:
6775 case glslang::EOpSubgroupAny:
6776 case glslang::EOpSubgroupAllEqual:
6777 builder.addCapability(spv::CapabilityGroupNonUniform);
6778 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6779 break;
6780 case glslang::EOpSubgroupBroadcast:
6781 case glslang::EOpSubgroupBroadcastFirst:
6782 case glslang::EOpSubgroupBallot:
6783 case glslang::EOpSubgroupInverseBallot:
6784 case glslang::EOpSubgroupBallotBitExtract:
6785 case glslang::EOpSubgroupBallotBitCount:
6786 case glslang::EOpSubgroupBallotInclusiveBitCount:
6787 case glslang::EOpSubgroupBallotExclusiveBitCount:
6788 case glslang::EOpSubgroupBallotFindLSB:
6789 case glslang::EOpSubgroupBallotFindMSB:
6790 builder.addCapability(spv::CapabilityGroupNonUniform);
6791 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6792 break;
6793 case glslang::EOpSubgroupShuffle:
6794 case glslang::EOpSubgroupShuffleXor:
6795 builder.addCapability(spv::CapabilityGroupNonUniform);
6796 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6797 break;
6798 case glslang::EOpSubgroupShuffleUp:
6799 case glslang::EOpSubgroupShuffleDown:
6800 builder.addCapability(spv::CapabilityGroupNonUniform);
6801 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6802 break;
6803 case glslang::EOpSubgroupAdd:
6804 case glslang::EOpSubgroupMul:
6805 case glslang::EOpSubgroupMin:
6806 case glslang::EOpSubgroupMax:
6807 case glslang::EOpSubgroupAnd:
6808 case glslang::EOpSubgroupOr:
6809 case glslang::EOpSubgroupXor:
6810 case glslang::EOpSubgroupInclusiveAdd:
6811 case glslang::EOpSubgroupInclusiveMul:
6812 case glslang::EOpSubgroupInclusiveMin:
6813 case glslang::EOpSubgroupInclusiveMax:
6814 case glslang::EOpSubgroupInclusiveAnd:
6815 case glslang::EOpSubgroupInclusiveOr:
6816 case glslang::EOpSubgroupInclusiveXor:
6817 case glslang::EOpSubgroupExclusiveAdd:
6818 case glslang::EOpSubgroupExclusiveMul:
6819 case glslang::EOpSubgroupExclusiveMin:
6820 case glslang::EOpSubgroupExclusiveMax:
6821 case glslang::EOpSubgroupExclusiveAnd:
6822 case glslang::EOpSubgroupExclusiveOr:
6823 case glslang::EOpSubgroupExclusiveXor:
6824 builder.addCapability(spv::CapabilityGroupNonUniform);
6825 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6826 break;
6827 case glslang::EOpSubgroupClusteredAdd:
6828 case glslang::EOpSubgroupClusteredMul:
6829 case glslang::EOpSubgroupClusteredMin:
6830 case glslang::EOpSubgroupClusteredMax:
6831 case glslang::EOpSubgroupClusteredAnd:
6832 case glslang::EOpSubgroupClusteredOr:
6833 case glslang::EOpSubgroupClusteredXor:
6834 builder.addCapability(spv::CapabilityGroupNonUniform);
6835 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6836 break;
6837 case glslang::EOpSubgroupQuadBroadcast:
6838 case glslang::EOpSubgroupQuadSwapHorizontal:
6839 case glslang::EOpSubgroupQuadSwapVertical:
6840 case glslang::EOpSubgroupQuadSwapDiagonal:
6841 builder.addCapability(spv::CapabilityGroupNonUniform);
6842 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6843 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006844#ifdef NV_EXTENSIONS
6845 case glslang::EOpSubgroupPartitionedAdd:
6846 case glslang::EOpSubgroupPartitionedMul:
6847 case glslang::EOpSubgroupPartitionedMin:
6848 case glslang::EOpSubgroupPartitionedMax:
6849 case glslang::EOpSubgroupPartitionedAnd:
6850 case glslang::EOpSubgroupPartitionedOr:
6851 case glslang::EOpSubgroupPartitionedXor:
6852 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6853 case glslang::EOpSubgroupPartitionedInclusiveMul:
6854 case glslang::EOpSubgroupPartitionedInclusiveMin:
6855 case glslang::EOpSubgroupPartitionedInclusiveMax:
6856 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6857 case glslang::EOpSubgroupPartitionedInclusiveOr:
6858 case glslang::EOpSubgroupPartitionedInclusiveXor:
6859 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6860 case glslang::EOpSubgroupPartitionedExclusiveMul:
6861 case glslang::EOpSubgroupPartitionedExclusiveMin:
6862 case glslang::EOpSubgroupPartitionedExclusiveMax:
6863 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6864 case glslang::EOpSubgroupPartitionedExclusiveOr:
6865 case glslang::EOpSubgroupPartitionedExclusiveXor:
6866 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6867 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6868 break;
6869#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006870 default: assert(0 && "Unhandled subgroup operation!");
6871 }
6872
6873 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6874 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6875 const bool isBool = typeProxy == glslang::EbtBool;
6876
6877 spv::Op opCode = spv::OpNop;
6878
6879 // Figure out which opcode to use.
6880 switch (op) {
6881 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6882 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6883 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6884 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6885 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6886 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6887 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6888 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6889 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6890 case glslang::EOpSubgroupBallotBitCount:
6891 case glslang::EOpSubgroupBallotInclusiveBitCount:
6892 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6893 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6894 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6895 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6896 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6897 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6898 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6899 case glslang::EOpSubgroupAdd:
6900 case glslang::EOpSubgroupInclusiveAdd:
6901 case glslang::EOpSubgroupExclusiveAdd:
6902 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006903#ifdef NV_EXTENSIONS
6904 case glslang::EOpSubgroupPartitionedAdd:
6905 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6906 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6907#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006908 if (isFloat) {
6909 opCode = spv::OpGroupNonUniformFAdd;
6910 } else {
6911 opCode = spv::OpGroupNonUniformIAdd;
6912 }
6913 break;
6914 case glslang::EOpSubgroupMul:
6915 case glslang::EOpSubgroupInclusiveMul:
6916 case glslang::EOpSubgroupExclusiveMul:
6917 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006918#ifdef NV_EXTENSIONS
6919 case glslang::EOpSubgroupPartitionedMul:
6920 case glslang::EOpSubgroupPartitionedInclusiveMul:
6921 case glslang::EOpSubgroupPartitionedExclusiveMul:
6922#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006923 if (isFloat) {
6924 opCode = spv::OpGroupNonUniformFMul;
6925 } else {
6926 opCode = spv::OpGroupNonUniformIMul;
6927 }
6928 break;
6929 case glslang::EOpSubgroupMin:
6930 case glslang::EOpSubgroupInclusiveMin:
6931 case glslang::EOpSubgroupExclusiveMin:
6932 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006933#ifdef NV_EXTENSIONS
6934 case glslang::EOpSubgroupPartitionedMin:
6935 case glslang::EOpSubgroupPartitionedInclusiveMin:
6936 case glslang::EOpSubgroupPartitionedExclusiveMin:
6937#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006938 if (isFloat) {
6939 opCode = spv::OpGroupNonUniformFMin;
6940 } else if (isUnsigned) {
6941 opCode = spv::OpGroupNonUniformUMin;
6942 } else {
6943 opCode = spv::OpGroupNonUniformSMin;
6944 }
6945 break;
6946 case glslang::EOpSubgroupMax:
6947 case glslang::EOpSubgroupInclusiveMax:
6948 case glslang::EOpSubgroupExclusiveMax:
6949 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006950#ifdef NV_EXTENSIONS
6951 case glslang::EOpSubgroupPartitionedMax:
6952 case glslang::EOpSubgroupPartitionedInclusiveMax:
6953 case glslang::EOpSubgroupPartitionedExclusiveMax:
6954#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006955 if (isFloat) {
6956 opCode = spv::OpGroupNonUniformFMax;
6957 } else if (isUnsigned) {
6958 opCode = spv::OpGroupNonUniformUMax;
6959 } else {
6960 opCode = spv::OpGroupNonUniformSMax;
6961 }
6962 break;
6963 case glslang::EOpSubgroupAnd:
6964 case glslang::EOpSubgroupInclusiveAnd:
6965 case glslang::EOpSubgroupExclusiveAnd:
6966 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006967#ifdef NV_EXTENSIONS
6968 case glslang::EOpSubgroupPartitionedAnd:
6969 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6970 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6971#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006972 if (isBool) {
6973 opCode = spv::OpGroupNonUniformLogicalAnd;
6974 } else {
6975 opCode = spv::OpGroupNonUniformBitwiseAnd;
6976 }
6977 break;
6978 case glslang::EOpSubgroupOr:
6979 case glslang::EOpSubgroupInclusiveOr:
6980 case glslang::EOpSubgroupExclusiveOr:
6981 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006982#ifdef NV_EXTENSIONS
6983 case glslang::EOpSubgroupPartitionedOr:
6984 case glslang::EOpSubgroupPartitionedInclusiveOr:
6985 case glslang::EOpSubgroupPartitionedExclusiveOr:
6986#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006987 if (isBool) {
6988 opCode = spv::OpGroupNonUniformLogicalOr;
6989 } else {
6990 opCode = spv::OpGroupNonUniformBitwiseOr;
6991 }
6992 break;
6993 case glslang::EOpSubgroupXor:
6994 case glslang::EOpSubgroupInclusiveXor:
6995 case glslang::EOpSubgroupExclusiveXor:
6996 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006997#ifdef NV_EXTENSIONS
6998 case glslang::EOpSubgroupPartitionedXor:
6999 case glslang::EOpSubgroupPartitionedInclusiveXor:
7000 case glslang::EOpSubgroupPartitionedExclusiveXor:
7001#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007002 if (isBool) {
7003 opCode = spv::OpGroupNonUniformLogicalXor;
7004 } else {
7005 opCode = spv::OpGroupNonUniformBitwiseXor;
7006 }
7007 break;
7008 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7009 case glslang::EOpSubgroupQuadSwapHorizontal:
7010 case glslang::EOpSubgroupQuadSwapVertical:
7011 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7012 default: assert(0 && "Unhandled subgroup operation!");
7013 }
7014
John Kessenich149afc32018-08-14 13:31:43 -06007015 // get the right Group Operation
7016 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007017 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007018 default:
7019 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007020 case glslang::EOpSubgroupBallotBitCount:
7021 case glslang::EOpSubgroupAdd:
7022 case glslang::EOpSubgroupMul:
7023 case glslang::EOpSubgroupMin:
7024 case glslang::EOpSubgroupMax:
7025 case glslang::EOpSubgroupAnd:
7026 case glslang::EOpSubgroupOr:
7027 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007028 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007029 break;
7030 case glslang::EOpSubgroupBallotInclusiveBitCount:
7031 case glslang::EOpSubgroupInclusiveAdd:
7032 case glslang::EOpSubgroupInclusiveMul:
7033 case glslang::EOpSubgroupInclusiveMin:
7034 case glslang::EOpSubgroupInclusiveMax:
7035 case glslang::EOpSubgroupInclusiveAnd:
7036 case glslang::EOpSubgroupInclusiveOr:
7037 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007038 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007039 break;
7040 case glslang::EOpSubgroupBallotExclusiveBitCount:
7041 case glslang::EOpSubgroupExclusiveAdd:
7042 case glslang::EOpSubgroupExclusiveMul:
7043 case glslang::EOpSubgroupExclusiveMin:
7044 case glslang::EOpSubgroupExclusiveMax:
7045 case glslang::EOpSubgroupExclusiveAnd:
7046 case glslang::EOpSubgroupExclusiveOr:
7047 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007048 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007049 break;
7050 case glslang::EOpSubgroupClusteredAdd:
7051 case glslang::EOpSubgroupClusteredMul:
7052 case glslang::EOpSubgroupClusteredMin:
7053 case glslang::EOpSubgroupClusteredMax:
7054 case glslang::EOpSubgroupClusteredAnd:
7055 case glslang::EOpSubgroupClusteredOr:
7056 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007057 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007058 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007059#ifdef NV_EXTENSIONS
7060 case glslang::EOpSubgroupPartitionedAdd:
7061 case glslang::EOpSubgroupPartitionedMul:
7062 case glslang::EOpSubgroupPartitionedMin:
7063 case glslang::EOpSubgroupPartitionedMax:
7064 case glslang::EOpSubgroupPartitionedAnd:
7065 case glslang::EOpSubgroupPartitionedOr:
7066 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007067 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007068 break;
7069 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7070 case glslang::EOpSubgroupPartitionedInclusiveMul:
7071 case glslang::EOpSubgroupPartitionedInclusiveMin:
7072 case glslang::EOpSubgroupPartitionedInclusiveMax:
7073 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7074 case glslang::EOpSubgroupPartitionedInclusiveOr:
7075 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007076 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007077 break;
7078 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7079 case glslang::EOpSubgroupPartitionedExclusiveMul:
7080 case glslang::EOpSubgroupPartitionedExclusiveMin:
7081 case glslang::EOpSubgroupPartitionedExclusiveMax:
7082 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7083 case glslang::EOpSubgroupPartitionedExclusiveOr:
7084 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007085 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007086 break;
7087#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007088 }
7089
John Kessenich149afc32018-08-14 13:31:43 -06007090 // build the instruction
7091 std::vector<spv::IdImmediate> spvGroupOperands;
7092
7093 // Every operation begins with the Execution Scope operand.
7094 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7095 spvGroupOperands.push_back(executionScope);
7096
7097 // Next, for all operations that use a Group Operation, push that as an operand.
7098 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007099 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007100 spvGroupOperands.push_back(groupOperand);
7101 }
7102
John Kessenich66011cb2018-03-06 16:12:04 -07007103 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007104 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7105 spv::IdImmediate operand = { true, *opIt };
7106 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007107 }
7108
7109 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007110 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007111 switch (op) {
7112 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007113 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7114 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7115 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7116 }
7117 if (directionId != spv::NoResult) {
7118 spv::IdImmediate direction = { true, directionId };
7119 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007120 }
7121
7122 return builder.createOp(opCode, typeId, spvGroupOperands);
7123}
7124
John Kessenich5e4b1242015-08-06 22:53:06 -06007125spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007126{
John Kessenich66011cb2018-03-06 16:12:04 -07007127 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7128 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007129
John Kessenich140f3df2015-06-26 16:58:36 -06007130 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007131 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007132 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007133 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007134 spv::Id typeId0 = 0;
7135 if (consumedOperands > 0)
7136 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007137 spv::Id typeId1 = 0;
7138 if (consumedOperands > 1)
7139 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007140 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007141
7142 switch (op) {
7143 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007144 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007145 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007146 else if (isUnsigned)
7147 libCall = spv::GLSLstd450UMin;
7148 else
7149 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007150 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007151 break;
7152 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007153 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007154 break;
7155 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007156 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007157 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007158 else if (isUnsigned)
7159 libCall = spv::GLSLstd450UMax;
7160 else
7161 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007162 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007163 break;
7164 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007165 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007166 break;
7167 case glslang::EOpDot:
7168 opCode = spv::OpDot;
7169 break;
7170 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007171 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007172 break;
7173
7174 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007175 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007176 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007177 else if (isUnsigned)
7178 libCall = spv::GLSLstd450UClamp;
7179 else
7180 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007181 builder.promoteScalar(precision, operands.front(), operands[1]);
7182 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007183 break;
7184 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007185 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7186 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007187 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007188 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007189 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007190 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007191 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007192 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007193 break;
7194 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007195 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007196 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007197 break;
7198 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007199 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007200 builder.promoteScalar(precision, operands[0], operands[2]);
7201 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007202 break;
7203
7204 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007205 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007206 break;
7207 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007208 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007209 break;
7210 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007211 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007212 break;
7213 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007214 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007215 break;
7216 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007217 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007218 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007219 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007220#ifdef AMD_EXTENSIONS
7221 if (typeProxy == glslang::EbtFloat16)
7222 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7223#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007224 libCall = spv::GLSLstd450InterpolateAtSample;
7225 break;
7226 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007227#ifdef AMD_EXTENSIONS
7228 if (typeProxy == glslang::EbtFloat16)
7229 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7230#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007231 libCall = spv::GLSLstd450InterpolateAtOffset;
7232 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007233 case glslang::EOpAddCarry:
7234 opCode = spv::OpIAddCarry;
7235 typeId = builder.makeStructResultType(typeId0, typeId0);
7236 consumedOperands = 2;
7237 break;
7238 case glslang::EOpSubBorrow:
7239 opCode = spv::OpISubBorrow;
7240 typeId = builder.makeStructResultType(typeId0, typeId0);
7241 consumedOperands = 2;
7242 break;
7243 case glslang::EOpUMulExtended:
7244 opCode = spv::OpUMulExtended;
7245 typeId = builder.makeStructResultType(typeId0, typeId0);
7246 consumedOperands = 2;
7247 break;
7248 case glslang::EOpIMulExtended:
7249 opCode = spv::OpSMulExtended;
7250 typeId = builder.makeStructResultType(typeId0, typeId0);
7251 consumedOperands = 2;
7252 break;
7253 case glslang::EOpBitfieldExtract:
7254 if (isUnsigned)
7255 opCode = spv::OpBitFieldUExtract;
7256 else
7257 opCode = spv::OpBitFieldSExtract;
7258 break;
7259 case glslang::EOpBitfieldInsert:
7260 opCode = spv::OpBitFieldInsert;
7261 break;
7262
7263 case glslang::EOpFma:
7264 libCall = spv::GLSLstd450Fma;
7265 break;
7266 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007267 {
7268 libCall = spv::GLSLstd450FrexpStruct;
7269 assert(builder.isPointerType(typeId1));
7270 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007271 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007272#ifdef AMD_EXTENSIONS
7273 if (width == 16)
7274 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7275 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7276#endif
Rex Xu470026f2017-03-29 17:12:40 +08007277 if (builder.getNumComponents(operands[0]) == 1)
7278 frexpIntType = builder.makeIntegerType(width, true);
7279 else
7280 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7281 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7282 consumedOperands = 1;
7283 }
John Kessenich55e7d112015-11-15 21:33:39 -07007284 break;
7285 case glslang::EOpLdexp:
7286 libCall = spv::GLSLstd450Ldexp;
7287 break;
7288
Rex Xu574ab042016-04-14 16:53:07 +08007289 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007290 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007291
John Kessenich66011cb2018-03-06 16:12:04 -07007292 case glslang::EOpSubgroupBroadcast:
7293 case glslang::EOpSubgroupBallotBitExtract:
7294 case glslang::EOpSubgroupShuffle:
7295 case glslang::EOpSubgroupShuffleXor:
7296 case glslang::EOpSubgroupShuffleUp:
7297 case glslang::EOpSubgroupShuffleDown:
7298 case glslang::EOpSubgroupClusteredAdd:
7299 case glslang::EOpSubgroupClusteredMul:
7300 case glslang::EOpSubgroupClusteredMin:
7301 case glslang::EOpSubgroupClusteredMax:
7302 case glslang::EOpSubgroupClusteredAnd:
7303 case glslang::EOpSubgroupClusteredOr:
7304 case glslang::EOpSubgroupClusteredXor:
7305 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007306#ifdef NV_EXTENSIONS
7307 case glslang::EOpSubgroupPartitionedAdd:
7308 case glslang::EOpSubgroupPartitionedMul:
7309 case glslang::EOpSubgroupPartitionedMin:
7310 case glslang::EOpSubgroupPartitionedMax:
7311 case glslang::EOpSubgroupPartitionedAnd:
7312 case glslang::EOpSubgroupPartitionedOr:
7313 case glslang::EOpSubgroupPartitionedXor:
7314 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7315 case glslang::EOpSubgroupPartitionedInclusiveMul:
7316 case glslang::EOpSubgroupPartitionedInclusiveMin:
7317 case glslang::EOpSubgroupPartitionedInclusiveMax:
7318 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7319 case glslang::EOpSubgroupPartitionedInclusiveOr:
7320 case glslang::EOpSubgroupPartitionedInclusiveXor:
7321 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7322 case glslang::EOpSubgroupPartitionedExclusiveMul:
7323 case glslang::EOpSubgroupPartitionedExclusiveMin:
7324 case glslang::EOpSubgroupPartitionedExclusiveMax:
7325 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7326 case glslang::EOpSubgroupPartitionedExclusiveOr:
7327 case glslang::EOpSubgroupPartitionedExclusiveXor:
7328#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007329 return createSubgroupOperation(op, typeId, operands, typeProxy);
7330
Rex Xu9d93a232016-05-05 12:30:44 +08007331#ifdef AMD_EXTENSIONS
7332 case glslang::EOpSwizzleInvocations:
7333 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7334 libCall = spv::SwizzleInvocationsAMD;
7335 break;
7336 case glslang::EOpSwizzleInvocationsMasked:
7337 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7338 libCall = spv::SwizzleInvocationsMaskedAMD;
7339 break;
7340 case glslang::EOpWriteInvocation:
7341 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7342 libCall = spv::WriteInvocationAMD;
7343 break;
7344
7345 case glslang::EOpMin3:
7346 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7347 if (isFloat)
7348 libCall = spv::FMin3AMD;
7349 else {
7350 if (isUnsigned)
7351 libCall = spv::UMin3AMD;
7352 else
7353 libCall = spv::SMin3AMD;
7354 }
7355 break;
7356 case glslang::EOpMax3:
7357 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7358 if (isFloat)
7359 libCall = spv::FMax3AMD;
7360 else {
7361 if (isUnsigned)
7362 libCall = spv::UMax3AMD;
7363 else
7364 libCall = spv::SMax3AMD;
7365 }
7366 break;
7367 case glslang::EOpMid3:
7368 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7369 if (isFloat)
7370 libCall = spv::FMid3AMD;
7371 else {
7372 if (isUnsigned)
7373 libCall = spv::UMid3AMD;
7374 else
7375 libCall = spv::SMid3AMD;
7376 }
7377 break;
7378
7379 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007380 if (typeProxy == glslang::EbtFloat16)
7381 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007382 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7383 libCall = spv::InterpolateAtVertexAMD;
7384 break;
7385#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007386 case glslang::EOpBarrier:
7387 {
7388 // This is for the extended controlBarrier function, with four operands.
7389 // The unextended barrier() goes through createNoArgOperation.
7390 assert(operands.size() == 4);
7391 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7392 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7393 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7394 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007395 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7396 spv::MemorySemanticsMakeVisibleKHRMask |
7397 spv::MemorySemanticsOutputMemoryKHRMask |
7398 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007399 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7400 }
7401 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7402 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7403 }
7404 return 0;
7405 }
7406 break;
7407 case glslang::EOpMemoryBarrier:
7408 {
7409 // This is for the extended memoryBarrier function, with three operands.
7410 // The unextended memoryBarrier() goes through createNoArgOperation.
7411 assert(operands.size() == 3);
7412 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7413 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7414 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007415 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7416 spv::MemorySemanticsMakeVisibleKHRMask |
7417 spv::MemorySemanticsOutputMemoryKHRMask |
7418 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007419 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7420 }
7421 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7422 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7423 }
7424 return 0;
7425 }
7426 break;
Chao Chen3c366992018-09-19 11:41:59 -07007427
7428#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007429 case glslang::EOpReportIntersectionNV:
7430 {
7431 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007432 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007433 }
7434 break;
7435 case glslang::EOpTraceNV:
7436 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007437 builder.createNoResultOp(spv::OpTraceNV, operands);
7438 return 0;
7439 }
7440 break;
7441 case glslang::EOpExecuteCallableNV:
7442 {
7443 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007444 return 0;
7445 }
7446 break;
Chao Chen3c366992018-09-19 11:41:59 -07007447 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7448 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7449 return 0;
7450#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007451 case glslang::EOpCooperativeMatrixMulAdd:
7452 opCode = spv::OpCooperativeMatrixMulAddNV;
7453 break;
7454
John Kessenich140f3df2015-06-26 16:58:36 -06007455 default:
7456 return 0;
7457 }
7458
7459 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007460 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007461 // Use an extended instruction from the standard library.
7462 // Construct the call arguments, without modifying the original operands vector.
7463 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7464 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007465 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007466 } else if (opCode == spv::OpDot && !isFloat) {
7467 // int dot(int, int)
7468 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7469 const int componentCount = builder.getNumComponents(operands[0]);
7470 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7471 builder.setPrecision(mulOp, precision);
7472 id = builder.createCompositeExtract(mulOp, typeId, 0);
7473 for (int i = 1; i < componentCount; ++i) {
7474 builder.setPrecision(id, precision);
7475 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7476 }
John Kessenich2359bd02015-12-06 19:29:11 -07007477 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007478 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007479 case 0:
7480 // should all be handled by visitAggregate and createNoArgOperation
7481 assert(0);
7482 return 0;
7483 case 1:
7484 // should all be handled by createUnaryOperation
7485 assert(0);
7486 return 0;
7487 case 2:
7488 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7489 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007490 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007491 // anything 3 or over doesn't have l-value operands, so all should be consumed
7492 assert(consumedOperands == operands.size());
7493 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007494 break;
7495 }
7496 }
7497
John Kessenich55e7d112015-11-15 21:33:39 -07007498 // Decode the return types that were structures
7499 switch (op) {
7500 case glslang::EOpAddCarry:
7501 case glslang::EOpSubBorrow:
7502 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7503 id = builder.createCompositeExtract(id, typeId0, 0);
7504 break;
7505 case glslang::EOpUMulExtended:
7506 case glslang::EOpIMulExtended:
7507 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7508 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7509 break;
7510 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007511 {
7512 assert(operands.size() == 2);
7513 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7514 // "exp" is floating-point type (from HLSL intrinsic)
7515 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7516 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7517 builder.createStore(member1, operands[1]);
7518 } else
7519 // "exp" is integer type (from GLSL built-in function)
7520 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7521 id = builder.createCompositeExtract(id, typeId0, 0);
7522 }
John Kessenich55e7d112015-11-15 21:33:39 -07007523 break;
7524 default:
7525 break;
7526 }
7527
John Kessenich32cfd492016-02-02 12:37:46 -07007528 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007529}
7530
Rex Xu9d93a232016-05-05 12:30:44 +08007531// Intrinsics with no arguments (or no return value, and no precision).
7532spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007533{
Jeff Bolz36831c92018-09-05 10:11:41 -05007534 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7535 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007536
7537 switch (op) {
7538 case glslang::EOpEmitVertex:
7539 builder.createNoResultOp(spv::OpEmitVertex);
7540 return 0;
7541 case glslang::EOpEndPrimitive:
7542 builder.createNoResultOp(spv::OpEndPrimitive);
7543 return 0;
7544 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007545 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007546 if (glslangIntermediate->usingVulkanMemoryModel()) {
7547 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7548 spv::MemorySemanticsOutputMemoryKHRMask |
7549 spv::MemorySemanticsAcquireReleaseMask);
7550 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7551 } else {
7552 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7553 }
John Kessenich82979362017-12-11 04:02:24 -07007554 } else {
7555 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7556 spv::MemorySemanticsWorkgroupMemoryMask |
7557 spv::MemorySemanticsAcquireReleaseMask);
7558 }
John Kessenich140f3df2015-06-26 16:58:36 -06007559 return 0;
7560 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007561 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7562 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007563 return 0;
7564 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007565 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7566 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007567 return 0;
7568 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007569 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7570 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007571 return 0;
7572 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007573 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7574 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007575 return 0;
7576 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007577 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7578 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007579 return 0;
7580 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007581 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7582 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007583 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007584 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007585 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007586 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007587 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007588 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007589 case glslang::EOpDeviceMemoryBarrier:
7590 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7591 spv::MemorySemanticsImageMemoryMask |
7592 spv::MemorySemanticsAcquireReleaseMask);
7593 return 0;
7594 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7595 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7596 spv::MemorySemanticsImageMemoryMask |
7597 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007598 return 0;
7599 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007600 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7601 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007602 return 0;
7603 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007604 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7605 spv::MemorySemanticsWorkgroupMemoryMask |
7606 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007607 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007608 case glslang::EOpSubgroupBarrier:
7609 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7610 spv::MemorySemanticsAcquireReleaseMask);
7611 return spv::NoResult;
7612 case glslang::EOpSubgroupMemoryBarrier:
7613 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7614 spv::MemorySemanticsAcquireReleaseMask);
7615 return spv::NoResult;
7616 case glslang::EOpSubgroupMemoryBarrierBuffer:
7617 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7618 spv::MemorySemanticsAcquireReleaseMask);
7619 return spv::NoResult;
7620 case glslang::EOpSubgroupMemoryBarrierImage:
7621 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7622 spv::MemorySemanticsAcquireReleaseMask);
7623 return spv::NoResult;
7624 case glslang::EOpSubgroupMemoryBarrierShared:
7625 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7626 spv::MemorySemanticsAcquireReleaseMask);
7627 return spv::NoResult;
7628 case glslang::EOpSubgroupElect: {
7629 std::vector<spv::Id> operands;
7630 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7631 }
Rex Xu9d93a232016-05-05 12:30:44 +08007632#ifdef AMD_EXTENSIONS
7633 case glslang::EOpTime:
7634 {
7635 std::vector<spv::Id> args; // Dummy arguments
7636 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7637 return builder.setPrecision(id, precision);
7638 }
7639#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007640#ifdef NV_EXTENSIONS
7641 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007642 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007643 return 0;
7644 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007645 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007646 return 0;
7647#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007648
7649 case glslang::EOpBeginInvocationInterlock:
7650 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7651 return 0;
7652 case glslang::EOpEndInvocationInterlock:
7653 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7654 return 0;
7655
Jeff Bolzba6170b2019-07-01 09:23:23 -05007656 case glslang::EOpIsHelperInvocation:
7657 {
7658 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007659 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7660 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7661 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007662 }
7663
amhagan91fb0092019-07-10 21:14:38 -04007664 case glslang::EOpReadClockSubgroupKHR: {
7665 std::vector<spv::Id> args;
7666 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7667 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7668 builder.addCapability(spv::CapabilityShaderClockKHR);
7669 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7670 }
7671
7672 case glslang::EOpReadClockDeviceKHR: {
7673 std::vector<spv::Id> args;
7674 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7675 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7676 builder.addCapability(spv::CapabilityShaderClockKHR);
7677 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7678 }
7679
John Kessenich140f3df2015-06-26 16:58:36 -06007680 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007681 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007682 return 0;
7683 }
7684}
7685
7686spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7687{
John Kessenich2f273362015-07-18 22:34:27 -06007688 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007689 spv::Id id;
7690 if (symbolValues.end() != iter) {
7691 id = iter->second;
7692 return id;
7693 }
7694
7695 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007696 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7697 auto forcedType = getForcedType(builtIn, symbol->getType());
7698 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007699 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007700 if (forcedType.second != spv::NoType)
7701 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007702
Rex Xuc884b4a2016-06-29 15:03:44 +08007703 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007704 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7705 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7706 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007707#ifdef NV_EXTENSIONS
7708 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7709#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007710 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007711 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007712 if (symbol->getQualifier().hasIndex())
7713 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7714 if (symbol->getQualifier().hasComponent())
7715 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007716 // atomic counters use this:
7717 if (symbol->getQualifier().hasOffset())
7718 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007719 }
7720
scygan2c864272016-05-18 18:09:17 +02007721 if (symbol->getQualifier().hasLocation())
7722 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007723 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007724 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007725 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007726 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007727 }
John Kessenich140f3df2015-06-26 16:58:36 -06007728 if (symbol->getQualifier().hasSet())
7729 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007730 else if (IsDescriptorResource(symbol->getType())) {
7731 // default to 0
7732 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7733 }
John Kessenich140f3df2015-06-26 16:58:36 -06007734 if (symbol->getQualifier().hasBinding())
7735 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007736 else if (IsDescriptorResource(symbol->getType())) {
7737 // default to 0
7738 builder.addDecoration(id, spv::DecorationBinding, 0);
7739 }
John Kessenich6c292d32016-02-15 20:58:50 -07007740 if (symbol->getQualifier().hasAttachment())
7741 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich7015bd62019-08-01 03:28:08 -06007742#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007743 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007744 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007745 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007746 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007747 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7748 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7749 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7750 }
7751 if (symbol->getQualifier().hasXfbOffset())
7752 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007753 }
John Kessenich7015bd62019-08-01 03:28:08 -06007754#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007755
Rex Xu1da878f2016-02-21 20:59:01 +08007756 if (symbol->getType().isImage()) {
7757 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007758 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007759 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007760 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007761 }
7762
John Kessenich9c14f772019-06-17 08:38:35 -06007763 // add built-in variable decoration
7764 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007765 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007766 }
John Kessenich140f3df2015-06-26 16:58:36 -06007767
John Kessenich5611c6d2018-04-05 11:25:02 -06007768 // nonuniform
7769 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7770
John Kessenichecba76f2017-01-06 00:34:48 -07007771#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007772 if (builtIn == spv::BuiltInSampleMask) {
7773 spv::Decoration decoration;
7774 // GL_NV_sample_mask_override_coverage extension
7775 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007776 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007777 else
7778 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007779 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007780 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007781 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007782 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7783 }
7784 }
chaoc771d89f2017-01-13 01:10:53 -08007785 else if (builtIn == spv::BuiltInLayer) {
7786 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007787 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007788 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007789 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7790 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7791 }
John Kessenichb41bff62017-08-11 13:07:17 -06007792 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007793 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7794 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007795 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7796 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7797 }
7798 }
7799
chaoc6e5acae2016-12-20 13:28:52 -08007800 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007801 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007802 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007803 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7804 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007805 if (symbol->getQualifier().pervertexNV) {
7806 builder.addDecoration(id, spv::DecorationPerVertexNV);
7807 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7808 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7809 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007810#endif
7811
John Kessenich5d610ee2018-03-07 18:05:55 -07007812 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7813 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7814 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7815 symbol->getType().getQualifier().semanticName);
7816 }
7817
John Kessenich7015bd62019-08-01 03:28:08 -06007818 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007819 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7820 }
7821
John Kessenich140f3df2015-06-26 16:58:36 -06007822 return id;
7823}
7824
Chao Chen3c366992018-09-19 11:41:59 -07007825#ifdef NV_EXTENSIONS
7826// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7827void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7828{
7829 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007830 if (qualifier.perPrimitiveNV) {
7831 // Need to add capability/extension for fragment shader.
7832 // Mesh shader already adds this by default.
7833 if (glslangIntermediate->getStage() == EShLangFragment) {
7834 builder.addCapability(spv::CapabilityMeshShadingNV);
7835 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7836 }
Chao Chen3c366992018-09-19 11:41:59 -07007837 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007838 }
Chao Chen3c366992018-09-19 11:41:59 -07007839 if (qualifier.perViewNV)
7840 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7841 if (qualifier.perTaskNV)
7842 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7843 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007844 if (qualifier.perPrimitiveNV) {
7845 // Need to add capability/extension for fragment shader.
7846 // Mesh shader already adds this by default.
7847 if (glslangIntermediate->getStage() == EShLangFragment) {
7848 builder.addCapability(spv::CapabilityMeshShadingNV);
7849 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7850 }
Chao Chen3c366992018-09-19 11:41:59 -07007851 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007852 }
Chao Chen3c366992018-09-19 11:41:59 -07007853 if (qualifier.perViewNV)
7854 builder.addDecoration(id, spv::DecorationPerViewNV);
7855 if (qualifier.perTaskNV)
7856 builder.addDecoration(id, spv::DecorationPerTaskNV);
7857 }
7858}
7859#endif
7860
John Kessenich55e7d112015-11-15 21:33:39 -07007861// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007862// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007863//
7864// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7865//
7866// Recursively walk the nodes. The nodes form a tree whose leaves are
7867// regular constants, which themselves are trees that createSpvConstant()
7868// recursively walks. So, this function walks the "top" of the tree:
7869// - emit specialization constant-building instructions for specConstant
7870// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007871spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007872{
John Kessenich7cc0e282016-03-20 00:46:02 -06007873 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007874
qining4f4bb812016-04-03 23:55:17 -04007875 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007876 if (! node.getQualifier().specConstant) {
7877 // hand off to the non-spec-constant path
7878 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7879 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007880 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007881 nextConst, false);
7882 }
7883
7884 // We now know we have a specialization constant to build
7885
John Kessenichd94c0032016-05-30 19:29:40 -06007886 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007887 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7888 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7889 std::vector<spv::Id> dimConstId;
7890 for (int dim = 0; dim < 3; ++dim) {
7891 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7892 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007893 if (specConst) {
7894 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7895 glslangIntermediate->getLocalSizeSpecId(dim));
7896 }
qining4f4bb812016-04-03 23:55:17 -04007897 }
7898 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7899 }
7900
7901 // An AST node labelled as specialization constant should be a symbol node.
7902 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7903 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007904 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007905 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007906 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7907 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7908 // will set the builder into spec constant op instruction generating mode.
7909 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007910 result = accessChainLoad(sub_tree->getType());
7911 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007912 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007913 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007914 } else {
7915 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007916 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007917 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007918 builder.addName(result, sn->getName().c_str());
7919 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007920 }
qining4f4bb812016-04-03 23:55:17 -04007921
7922 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7923 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007924 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007925 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007926}
7927
John Kessenich140f3df2015-06-26 16:58:36 -06007928// Use 'consts' as the flattened glslang source of scalar constants to recursively
7929// build the aggregate SPIR-V constant.
7930//
7931// If there are not enough elements present in 'consts', 0 will be substituted;
7932// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7933//
qining08408382016-03-21 09:51:37 -04007934spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007935{
7936 // vector of constants for SPIR-V
7937 std::vector<spv::Id> spvConsts;
7938
7939 // Type is used for struct and array constants
7940 spv::Id typeId = convertGlslangToSpvType(glslangType);
7941
7942 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007943 glslang::TType elementType(glslangType, 0);
7944 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007945 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007946 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007947 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007948 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007949 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007950 } else if (glslangType.isCoopMat()) {
7951 glslang::TType componentType(glslangType.getBasicType());
7952 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007953 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007954 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7955 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007956 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007957 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007958 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7959 bool zero = nextConst >= consts.size();
7960 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007961 case glslang::EbtInt8:
7962 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7963 break;
7964 case glslang::EbtUint8:
7965 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7966 break;
7967 case glslang::EbtInt16:
7968 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7969 break;
7970 case glslang::EbtUint16:
7971 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7972 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007973 case glslang::EbtInt:
7974 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7975 break;
7976 case glslang::EbtUint:
7977 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7978 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007979 case glslang::EbtInt64:
7980 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7981 break;
7982 case glslang::EbtUint64:
7983 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7984 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007985 case glslang::EbtFloat:
7986 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7987 break;
7988 case glslang::EbtDouble:
7989 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7990 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007991 case glslang::EbtFloat16:
7992 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7993 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007994 case glslang::EbtBool:
7995 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7996 break;
7997 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007998 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007999 break;
8000 }
8001 ++nextConst;
8002 }
8003 } else {
8004 // we have a non-aggregate (scalar) constant
8005 bool zero = nextConst >= consts.size();
8006 spv::Id scalar = 0;
8007 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07008008 case glslang::EbtInt8:
8009 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8010 break;
8011 case glslang::EbtUint8:
8012 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8013 break;
8014 case glslang::EbtInt16:
8015 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8016 break;
8017 case glslang::EbtUint16:
8018 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8019 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008020 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07008021 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008022 break;
8023 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07008024 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008025 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008026 case glslang::EbtInt64:
8027 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8028 break;
8029 case glslang::EbtUint64:
8030 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8031 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008032 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07008033 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008034 break;
8035 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008036 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008037 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008038 case glslang::EbtFloat16:
8039 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8040 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008041 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07008042 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008043 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008044 case glslang::EbtReference:
8045 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8046 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8047 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008048 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008049 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008050 break;
8051 }
8052 ++nextConst;
8053 return scalar;
8054 }
8055
8056 return builder.makeCompositeConstant(typeId, spvConsts);
8057}
8058
John Kessenich7c1aa102015-10-15 13:29:11 -06008059// Return true if the node is a constant or symbol whose reading has no
8060// non-trivial observable cost or effect.
8061bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8062{
8063 // don't know what this is
8064 if (node == nullptr)
8065 return false;
8066
8067 // a constant is safe
8068 if (node->getAsConstantUnion() != nullptr)
8069 return true;
8070
8071 // not a symbol means non-trivial
8072 if (node->getAsSymbolNode() == nullptr)
8073 return false;
8074
8075 // a symbol, depends on what's being read
8076 switch (node->getType().getQualifier().storage) {
8077 case glslang::EvqTemporary:
8078 case glslang::EvqGlobal:
8079 case glslang::EvqIn:
8080 case glslang::EvqInOut:
8081 case glslang::EvqConst:
8082 case glslang::EvqConstReadOnly:
8083 case glslang::EvqUniform:
8084 return true;
8085 default:
8086 return false;
8087 }
qining25262b32016-05-06 17:25:16 -04008088}
John Kessenich7c1aa102015-10-15 13:29:11 -06008089
8090// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008091// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008092// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008093// Return true if trivial.
8094bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8095{
8096 if (node == nullptr)
8097 return false;
8098
John Kessenich84cc15f2017-05-24 16:44:47 -06008099 // count non scalars as trivial, as well as anything coming from HLSL
8100 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008101 return true;
8102
John Kessenich7c1aa102015-10-15 13:29:11 -06008103 // symbols and constants are trivial
8104 if (isTrivialLeaf(node))
8105 return true;
8106
8107 // otherwise, it needs to be a simple operation or one or two leaf nodes
8108
8109 // not a simple operation
8110 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8111 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8112 if (binaryNode == nullptr && unaryNode == nullptr)
8113 return false;
8114
8115 // not on leaf nodes
8116 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8117 return false;
8118
8119 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8120 return false;
8121 }
8122
8123 switch (node->getAsOperator()->getOp()) {
8124 case glslang::EOpLogicalNot:
8125 case glslang::EOpConvIntToBool:
8126 case glslang::EOpConvUintToBool:
8127 case glslang::EOpConvFloatToBool:
8128 case glslang::EOpConvDoubleToBool:
8129 case glslang::EOpEqual:
8130 case glslang::EOpNotEqual:
8131 case glslang::EOpLessThan:
8132 case glslang::EOpGreaterThan:
8133 case glslang::EOpLessThanEqual:
8134 case glslang::EOpGreaterThanEqual:
8135 case glslang::EOpIndexDirect:
8136 case glslang::EOpIndexDirectStruct:
8137 case glslang::EOpLogicalXor:
8138 case glslang::EOpAny:
8139 case glslang::EOpAll:
8140 return true;
8141 default:
8142 return false;
8143 }
8144}
8145
8146// Emit short-circuiting code, where 'right' is never evaluated unless
8147// the left side is true (for &&) or false (for ||).
8148spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8149{
8150 spv::Id boolTypeId = builder.makeBoolType();
8151
8152 // emit left operand
8153 builder.clearAccessChain();
8154 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008155 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008156
8157 // Operands to accumulate OpPhi operands
8158 std::vector<spv::Id> phiOperands;
8159 // accumulate left operand's phi information
8160 phiOperands.push_back(leftId);
8161 phiOperands.push_back(builder.getBuildPoint()->getId());
8162
8163 // Make the two kinds of operation symmetric with a "!"
8164 // || => emit "if (! left) result = right"
8165 // && => emit "if ( left) result = right"
8166 //
8167 // TODO: this runtime "not" for || could be avoided by adding functionality
8168 // to 'builder' to have an "else" without an "then"
8169 if (op == glslang::EOpLogicalOr)
8170 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8171
8172 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008173 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008174
8175 // emit right operand as the "then" part of the "if"
8176 builder.clearAccessChain();
8177 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008178 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008179
8180 // accumulate left operand's phi information
8181 phiOperands.push_back(rightId);
8182 phiOperands.push_back(builder.getBuildPoint()->getId());
8183
8184 // finish the "if"
8185 ifBuilder.makeEndIf();
8186
8187 // phi together the two results
8188 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8189}
8190
Frank Henigman541f7bb2018-01-16 00:18:26 -05008191#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08008192// Return type Id of the imported set of extended instructions corresponds to the name.
8193// Import this set if it has not been imported yet.
8194spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8195{
8196 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8197 return extBuiltinMap[name];
8198 else {
Rex Xu51596642016-09-21 18:56:12 +08008199 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008200 spv::Id extBuiltins = builder.import(name);
8201 extBuiltinMap[name] = extBuiltins;
8202 return extBuiltins;
8203 }
8204}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008205#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008206
John Kessenich140f3df2015-06-26 16:58:36 -06008207}; // end anonymous namespace
8208
8209namespace glslang {
8210
John Kessenich68d78fd2015-07-12 19:28:10 -06008211void GetSpirvVersion(std::string& version)
8212{
John Kessenich9e55f632015-07-15 10:03:39 -06008213 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008214 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008215 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008216 version = buf;
8217}
8218
John Kessenicha372a3e2017-11-02 22:32:14 -06008219// For low-order part of the generator's magic number. Bump up
8220// when there is a change in the style (e.g., if SSA form changes,
8221// or a different instruction sequence to do something gets used).
8222int GetSpirvGeneratorVersion()
8223{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008224 // return 1; // start
8225 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008226 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008227 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008228 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008229 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8230 // versions 4 and 6 each generate OpArrayLength as it has long been done
8231 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008232}
8233
John Kessenich140f3df2015-06-26 16:58:36 -06008234// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008235void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008236{
8237 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008238 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008239 if (out.fail())
8240 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008241 for (int i = 0; i < (int)spirv.size(); ++i) {
8242 unsigned int word = spirv[i];
8243 out.write((const char*)&word, 4);
8244 }
8245 out.close();
8246}
8247
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008248// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008249void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008250{
8251 std::ofstream out;
8252 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008253 if (out.fail())
8254 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008255 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008256 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008257 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008258 if (varName != nullptr) {
8259 out << "\t #pragma once" << std::endl;
8260 out << "const uint32_t " << varName << "[] = {" << std::endl;
8261 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008262 const int WORDS_PER_LINE = 8;
8263 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8264 out << "\t";
8265 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8266 const unsigned int word = spirv[i + j];
8267 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8268 if (i + j + 1 < (int)spirv.size()) {
8269 out << ",";
8270 }
8271 }
8272 out << std::endl;
8273 }
Flavio15017db2017-02-15 14:29:33 -08008274 if (varName != nullptr) {
8275 out << "};";
8276 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008277 out.close();
8278}
8279
John Kessenich140f3df2015-06-26 16:58:36 -06008280//
8281// Set up the glslang traversal
8282//
John Kessenich4e11b612018-08-30 16:56:59 -06008283void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008284{
Lei Zhang17535f72016-05-04 15:55:59 -04008285 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008286 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008287}
8288
John Kessenich4e11b612018-08-30 16:56:59 -06008289void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008290 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008291{
John Kessenich140f3df2015-06-26 16:58:36 -06008292 TIntermNode* root = intermediate.getTreeRoot();
8293
8294 if (root == 0)
8295 return;
8296
John Kessenich4e11b612018-08-30 16:56:59 -06008297 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008298 if (options == nullptr)
8299 options = &defaultOptions;
8300
John Kessenich4e11b612018-08-30 16:56:59 -06008301 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008302
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008303 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008304 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008305 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008306 it.dumpSpv(spirv);
8307
GregFfb03a552018-03-29 11:49:14 -06008308#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008309 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8310 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008311 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8312 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008313 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008314 prelegalization = false;
8315 }
John Kessenich717c80a2018-08-23 15:17:10 -06008316
John Kessenich4e11b612018-08-30 16:56:59 -06008317 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008318 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008319
John Kessenich717c80a2018-08-23 15:17:10 -06008320 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008321 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008322
GregFcd1f1692017-09-21 18:40:22 -06008323#endif
8324
John Kessenich4e11b612018-08-30 16:56:59 -06008325 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008326}
8327
8328}; // end namespace glslang